How to implement basic (single value) route model binding in Laravel

Routing

Here is a basic overview of a 'web.php' route that show how route model binding works:

You can do this three ways depending on your requirements and time on hands:

1. With a GET
2. With a resource controller

Please note, route model binding doesn't work with POST routes.

Route model binding can work with one or more parameters. This example has more than one parameter.

How to do route model binding with a GET route:

Route::get('/articles/{category}/{slug}', function ($category, $slug) {
    $article = Article::where('slug', $slug)->first();

    if (!$article) {
        $redirection = Redirection::where('old_url', $category . '/' . $slug)->first();

        if ($redirection) {
            return redirect('/articles/' . $redirection->new_url);
        }
    }

    $article->timestamps = false;
    $article->views++;
    $article->save();
    $article->timestamps = true; // Otherwise diffForHumans() doesn't work

    return view('article', compact('article'));
});
lang-php