Laravel Routing to Controllers

Instead of defining all of your request handling logic as Closures in route files, it sometime better, especially for larger projects, to use a controller.

Routes to a Controller

NOTE

As of Laravel 8, the way routes point to a controller has changed. By default, Laravel 8 has no automatic controller declaration prefixing. This feature can be easily reactivated.

To point a route to a controller, you must provide an array that defines which controller class and method to call. First start by importing the desired controller class into the routes file. Then the first item in the array is the desired controller class, while the second item is the method as a string.

use App\Http\Controllers\PostsController;

Route::get('/', [PostController::class, 'show']);

Alternatively, it is possible to use a string that defines which controller class and method to call, which was common practice before Laravel 8. This does require making a small change to the RouteServiceProvider.php file. Find the line that defines protected $namespace and uncomment it.








 






















/**
  * The controller namespace for the application.
  *
  * When present, controller route declarations will automatically be prefixed with this namespace.
  *
  * @var string|null
  */
protected $namespace = 'App\\Http\\Controllers';

/**
  * Define your route model bindings, pattern filters, etc.
  *
  * @return void
  */
public function boot()
{
    $this->configureRateLimiting();

    $this->routes(function () {
        Route::prefix('api')
            ->middleware('api')
            ->namespace($this->namespace)
            ->group(base_path('routes/api.php'));

        Route::middleware('web')
            ->namespace($this->namespace)
            ->group(base_path('routes/web.php'));
    });
}

With that, a route can point to a controller by providing a string that defines which controller class and method to call. The first part of the string should be the name of the class. Then a @ and finally the name of the method. The final result would look something like this:

Route::get('/posts/{post}', 'PostsController@show');

Creating a Controller

Controllers are fundamental part of the Model-View-Controller (MVC) architecture that Laravel is build around. The above code will not work if there is not PostsController controller class. Controllers can be created in one of two ways: manually or through the artisan console. In either case, all controllers will reside in the app/Http/Controllers directory and will look something like this:

<?php

namespace App\Http\Controllers;


class PostsControllers extends Controller
{
  public function show($post) 
  {
    $posts = [
      'post-1' => 'This is my first post';
      'post-2' => 'This is my second post';
    ];

    if (!isset($posts[$post])) {
      abort(404, 'The post was not found.');
    }

    return view('post', [
      'post' => $posts[$post]
    ]);
  }
}

We will controllers in greater detail later in the course.