Hello friends. Today I will introduce you about Controllers in Laravel and how to use Controllers in Laravel.
1. Introduction
Instead of defining all the logic of handling your request in the routes.php
file, you may want to manage this by using Controller classes. Controllers can group related HTTP requests into the same class. Controllers are stored in app/Http/Controllers
.
2. Basic controller
Define controller
Below is an example of controller in laravel. We should note that all extended controller classes should inherit the Controller class provided by Laravel.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <?php namespace AppHttpControllers; use AppUser; use AppHttpControllersController; class UserController extends Controller { /** * Show the profile for the given user. * * @param int $id * @return View */ public function show($id) { return view('user.profile', ['user' => User::findOrFail($id)]); } } |
You can define a route to an controller action as follows:
1 2 | Route::get('user/{id}', ' <a class="__cf_email__" href="/cdn-cgi/l/email-protection">[email protected]</a> '); |
Now, when a request matches the URI address of the show
method route on the UserController
class, the route parameters will also be passed into the method.
Controller && Namespaces
You should note that we do not need to write down the full controller address when defining a route. We only need to define the controller name after the AppHttpController
namespace, because the RouteServiceProvider
loads the route files and the controllers in that route are specified after the AppHttpController
namespace. If you want to include your controllers in a subdirectory after the AppHttpController
namespace, you can simply call the name of that directory in the route as follows:
1 2 | Route::get('foo', 'Photos <a class="__cf_email__" href="/cdn-cgi/l/email-protection">[email protected]</a> '); |
3. Controller Middleware
Middleware can be assigned to controllers in your routes as follows:
1 2 | Route::get('profile', ' <a class="__cf_email__" href="/cdn-cgi/l/email-protection">[email protected]</a> ')->middleware('auth'); |
However, it is more convenient to define middleware from the controller’s contructor function. Using the middleware method from within your controller, you can easily assign middleware to the controller. You can even restrict the middleware to specific methods in the controller class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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'); } } |
4. Resource Controllers
Resource controllers make it easier to build RESTful controllers around resources. For example, you might want to create a controller that handles HTTP requests related to “photos” stored in your application. Using the Artisan make: controller statement, we can quickly create controllers:
1 2 | php artisan make:controller PhotoController --resource |
The Artisan command will generate the controller file at app/Http/Controllers/PhotoController.php
. The controller will include a method for the operation of the resource available.
Next, you may want to register a multi-resource route for the controller:
1 2 | Route::resource('photo', 'PhotoController'); |
This unique routing declaration creates multiple routes to handle a variety of RESTful action types for the “photo” resource. Similarly, the generated controller will have some root methods available for each action, including a note telling you which URIs and which HTTP methods (POST, GET, PUT, PATCH, DELETE) they handle. physical.
You can register multiple resource controllers as follows:
1 2 3 4 5 | Route::resources([ 'photos' => 'PhotoController', 'posts' => 'PostController' ]); |
Because HTML forms cannot add PUT
, PATCH
, DELETE
methods, you will need to add the _method
field to fake these actions from HTTP. Or use @method in the Laravel blade:
1 2 3 4 | <form action="/foo/bar" method="POST"> @method('PUT') </form> |
Partial resource routing
When declaring a route resource you can specify it to use a partial resource using only
or except
methods:
1 2 3 4 5 6 7 8 | Route::resource('photo', 'PhotoController', ['only' => [ 'index', 'show' ]]); Route::resource('photo', 'PhotoController', ['except' => [ 'create', 'store', 'update', 'destroy' ]]); |
Name the resource routing
By default, all resource controller actions have a name; However, you can override those names by passing a string of names of your choice:
1 2 3 4 | Route::resource('photo', 'PhotoController', ['names' => [ 'create' => 'photo.build' ]]); |
Name the parameter of the resource routing
By default, Route :: resource will create parameters for your resource routes based on the resource name. You can easily override each basic resource by passing parameters in the optional string. The parameters string should be an associative array of resource names and parameter names:
1 2 3 4 | Route::resource('user', 'AdminUserController', ['parameters' => [ 'user' => 'admin_user' ]]); |
The above example will generate the following URIs for the show routing of the resource:
/user/{admin_user}
5. Dependency Injection & Controllers
Constructor Injection
Laravel’s service container is used to handle all Laravel controllers. As a result, you can “type-hint” whatever dependencies your controller needs into the controller’s constructor. The dependencies will be automatically handled and added in the controller’s “instance”:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <?php namespace AppHttpControllers; use AppRepositoriesUserRepository; class UserController extends Controller { /** * The user repository instance. */ protected $users; /** * Create a new controller instance. * * @param UserRepository $users * @return void */ public function __construct(UserRepository $users) { $this->users = $users; } } |
Method Injection
In addition to constructor injection, you can also type-hint dependencies on controller methods. For example, let’s type-hint the IlluminateHttpRequest
instance into one of our methods:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | <?php namespace AppHttpControllers; use IlluminateHttpRequest; class UserController extends Controller { /** * Store a new user. * * @param Request $request * @return Response */ public function store(Request $request) { $name = $request->name; // } } |
If your controller’s method is also expecting input from the routing parameter, then simply list the arguments of the route behind the other dependencies. For example, if your routing is defined as follows:
Route::put('user/{id}', ' [email protected] ');
You can still type-hint IlluminateHttpRequest
and access your route parameter id by defining your controller method as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <?php namespace AppHttpControllers; use IlluminateHttpRequest; class UserController extends Controller { /** * Update the specified user. * * @param Request $request * @param string $id * @return Response */ public function update(Request $request, $id) { // } } |
6. Route Caching
If your application only uses controller routes, then you can use the advanced part of Laravel’s routing cache. Using routing caching will reduce the network time required to register all routes in your application. In some cases, your routing registration can be up to 100 times faster! To create routing memory, simply run the Artisan route: cache command:
php artisan route:cache
That’s all! Your routing cache file will be used instead of the app / Http / routes.php file. Remember, if you add any new routes, you need to create a new route cache. Therefore, you should only run the route: cache statement during project development.
To delete the route cache file without creating a new file, use the route: clear command:
php artisan route:clear
So I introduced the basic controller in Laravel. Reference: https://laravel.com/docs/5.8/controllers#controllers-and-namespaces