Laravel Controllers

Domains: Laravel

Laravel Controllers

Can group related request handling logic into a single class.

  • Are not required to extend a base class.
  • Also allow you to register middleware using a Closure.
  • Are stored in the app/Http/Controllers directory.

Basic Controllers

Controller Middleware

Route::get('profile', 'UserController@show')->middleware('auth');
Class UserController extends Controller
{ /**
     * Instantiate a new controller instance.
     * @return void
     */ public function __construct()
    { $this->middleware('auth'); $this->middleware('log')->only('index'); $this->middleware('subscribed')->except('store'); } }
  • You may even restrict the middleware to only certain methods on the controller class.
  • May be assigned to the controller's routes in your route files.
  • You may assign middleware to a subset of controller actions.

Resource Controllers

Php artisan make:controller PhotoController --resource
Route::resource('photos', 'PhotoController');
Route::resources([ 'photos' => 'PhotoController', 'posts' => 'PostController' ]);
  • You may register a resourceful route to the controller.
  • You may register many resource controllers at once by passing an array to the resources method.
  • Resource routing assigns the typical "CRUD" routes to a controller with a single line of code.

Dependency Injection & Controllers

Route Caching

Php artisan route:cache
Php artisan route:clear
  • To generate a route cache, just execute the route:cache Artisan command.
  • You may use the route:clear command to clear the route cache.
  • To use route caching, you must convert any Closure routes to controller classes.

Laravel Controllers — Structure map

Clickable & Draggable!

Laravel Controllers — Related pages: