Home >>Laravel Tutorial >Laravel Controllers
Route::get(‘base URI’,’controller@method’); <?php namespace App\Http\Controllers; use App\User; use App\Http\Controllers\Controller; 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 determine a route to this controller action like so: Route::get('user/{id}', 'UserController@show'); Promptly, when a provided request meets the particularised route URI, the show method on the UserController class will be administered. Also, it is obvious that the route parameters will also be declared and passed to the method. Controllers & Namespaces The most significant thing in laravel controller creation to note is that we did not require to define the full controller namespace when determining the controller route. Considering the RouteServiceProvider loads your route data files inside or within a route group that comprises the namespace, we only specified the part of the class name that appears after the App\Http\Controllers division of the namespace. If you prefer to nest your controllers deep-toned into the App\Http\Controllers record directory, apply the particular class name corresponding to the App\Http\Controllers root namespace. So, if your full controller class is App\Http\Controllers\Images\AdminController, you should register routes to the controller like so: Route::get('foo', 'Photos\AdminController@method'); Single Action Controllers If you would wish to assign or define a controller that only manipulates or handle a single operation, you may put or place a unique or a single__invoke method on the controller:
<?php namespace App\Http\Controllers; use App\User; use App\Http\Controllers\Controller; class ShowProfile extends Controller { /** * Show the profile for the given user. * * @param int $id * @return View */ public function __invoke($id) { return view('user.profile', ['user' => User::findOrFail($id)]); } }When enrolling routes for eligible as well as single action controllers, you do not require to define a method: Route::get('user/{id}', 'ShowProfile'); You can produce an invokable controller by utilising the --invokable selection of the make:controller Artisan command: php artisan make:controller ShowProfile --invokable Controller Middleware We have seen middleware already. Furthermore, it can be applied with controller also. Middleware may be assigned to the controller's routes in your route files: Route::get('profile', 'UserController@show')->middleware('auth'); Though, it is further advantageous to designate middleware within your controller's constructor. Applying the middleware method from your controller's laravel controller constructor, you may readily specify middleware to the controller's operation. You can indeed limit the middleware to particularly certain methods on the controller class:
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'); } }Controllers further authorise you to enrol middleware utilising a Closure which implements a convenient means to describe a middleware for a single controller externally determining a whole middleware class:
$this->middleware(function ($request, $next) { // ... return $next($request); });Resource Controllers laravel controller tutorial will lead to having an in-depth knowledge about the resource controllers. Laravel resource routing specifies or assigns the typical "CRUD" routes to a controller including a single line of code. For instance, you may crave to build or create a controller that controls all HTTP requests for "photos" cached by your application. Utilising the make:controller Artisan command, we may promptly create such a controller: php artisan make:controller PhotoController --resource This command as mentioned earlier will help to generate a controller at app/Http/Controllers/PhotoController.php. The controller will comprise a method for each of the accessible resource operations. Ensuing, you can record an original and resourceful route to the controller: Route::resource('photos', 'PhotoController'); This particular, as well as single route declaration, produces various routes to manipulate or handle a variety of activities on the resource. You can register multiple resource controllers at once by declaring an array to the resources method:
Route::resources([ 'photos' => 'PhotoController', 'posts' => 'PostController' ]);Specifying The Resource Model If you are using laravel controller creation method also utilising route model merging and would desire the resource controller's methods to type-hint a model instance, you can utilise the --model option when creating the controller: php artisan make:controller PhotoController --resource --model=Photo Spoofing Form Methods As HTML forms can't make PUT, PATCH, or DELETE requests, you will require to attach a hidden _method field to spoof these HTTP verbs. The @method Blade directive can produce this track for you:
<form action="/foo/bar" method="POST"> @method('PUT') </form>Partial Resource Routes When representing a resource route, you may define a subset of operations the controller should manage rather of the complete assortment of default actions:
Route::resource('photos', 'PhotoController')->only([ 'index', 'show' ]); Route::resource('photos', 'PhotoController')->except([ 'create', 'store', 'update', 'destroy' ]);API Resource Routes API Resource Routes consumes the resource routes thus when representing resource routes that will be consumed by APIs; you will generally need to eliminate routes that impersonate HTML templates such as create and edit. For support, you may apply the apiResource method to exclude these two routes automatically: Route::apiResource('photos', 'PhotoController'); You may designate multiple API resource controllers at once via enacting an array to the apiResources method:
Route::apiResources([ 'photos' => 'PhotoController', 'posts' => 'PostController' ]);To rapidly create an API resource controller laravel controller constructor that does not involves the create or edit methods, you should use the --api switch when establishing or executing the make:controller command: php artisan make:controller API/PhotoController --api Naming Resource Routes All resource controller operations or action have a route name by default; though, you are allowed to override these names by giving or passing a names array with your options:
Route::resource('photos', 'PhotoController')->names([ 'create' => 'photos.build' ]);Naming Resource Route Parameters Route::resource will generate by default the route parameters for your resource routes based on the "singularized" variant or version of the resource name. You can revoke this on a per-resource base by utilising the parameters method. The array carried into the parameters of laravel controller origination method should be an associative array of resource names and parameter names:
Route::resource('users', 'AdminUserController')->parameters([ 'users' => 'admin_user' ]);The example above produces the subsequent URIs for the resource's show route: /users/{admin_user} Localizing Resource URIs By default, Route::resource will generate resource URIs applying English verbs. If you want to confine the create and edit act verbs, you can utilise the Route::resourceVerbs method. It can be served in the boot program of your AppServiceProvider:
use Illuminate\Support\Facades\Route; /** * Bootstrap any application services. * * @return void */ public function boot() { Route::resourceVerbs([ 'create' => 'crear', 'edit' => 'editar', ]); }Once the verbs have been customised, a resource route enrolment such as Route::resource('photos', 'PhotoController') will provide the following URIs: /photos/clear /photos/{photo}/editar Supplementing Resource Controllers If you want to append additional routes to laravel controller creation and a resource controller exceeding the default inclination of resource routes, you should determine those routes before your call to Route::resource; otherwise, the routes specified by the resource method may involuntarily take priority superior your supplemental routes: Route::get('photos/popular', 'PhotoController@method'); Route::resource('photos', 'PhotoController');
<?php namespace App\Http\Controllers; use App\Repositories\UserRepository; 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; } }It is apparent that you may also type-hint any Laravel contract. If the package or container can resolve it, you can type-hint it. Depending on your application, inserting your dependencies within your controller may render greater testability. Method Injection In extension to laravel controller constructor injection, you may also type-hint dependencies on your controller's methods. A typical use-case for custom or method injection is inserting or injecting the Illuminate\Http\Request instance in your controller methods:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class UserController extends Controller { /** * Store a new user. * * @param Request $request * @return Response */ public function store(Request $request) { $name = $request->name; // } }If your controller method is further demanding input from a route parameter, list your program route arguments after your different other dependencies. For instance, if your route is determined or defined like so: Route::put('user/{id}', 'UserController@update'); You can yet type-hint the Illuminate\Http\Request and locate your id parameter by determining your controller method as follows:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class UserController extends Controller { /** * Update the given user. * * @param Request $request * @param string $id * @return Response */ public function update(Request $request, $id) { // } }