Laravel basic tutorial-controller-php Tutorial

Source: Internet
Author: User
Laravel basic tutorial-Introduction to controller HTTP controller

The controller allows you to encapsulate the corresponding routing business logic in the controller class for effective management, so that you do not need to concentrate all routing logic into routes. php files, resulting in code bloated and difficult to maintain. All controller classes are stored in the app/Http/Controllers directory.

Basic controller

A basic Controller should inherit from the App \ Http \ Controllers \ Controller class:

  User::findOrFail($id)]);  }}`

We can use the following method to route the controller behavior:

Route::get('user/{id}', 'UserController@showProfile');

Once the behavior of the controller is assigned to the route, the behavior of the controller is triggered every time the client requests the route. The showProfile method is executed every time the client requests the user/{id} route, and the parameters in the route are directly transmitted to this method.

Controller & namespace

You should know that you do not need to specify the controller namespace when defining the controller routing, but you only need to specify the class name. this is because the routes is automatically loaded in the RouteServiceProvider file. the PHP file has been specified with the root namespace App \ Http \ Controllers of the route Group;

If you want to use the php namespace in the App \ Http \ Controllers directory to nest or organize Controllers, you only need to specify the class name relative to App \ Http \ Controllers. Therefore, if all your controller classes are named App \ Http \ Controllers \ Photos \ AdminController, you can define the controller route as follows:

Route::get('foo', 'Photos\AdminController@method');
Named controller route

Just like defining a named route, we can also name a controller route:

Route::get('foo', ['uses' => 'FooController@method', 'as' => 'name']);

Once you name a route, you can use the route help method to quickly generate the resource address of the named route:

$url = route('name');
Controller middleware

Middleware can be allocated to the controller route as follows:

Route::get('profile', [  'middleware' => 'auth',  'uses' => 'UserController@showProfile']);

Of course, you can also directly use the middleware method in the controller class for middleware allocation. you can also only allow certain behaviors in the class to be restricted by the specified middleware:

class UserController extends Controller {  public function __construct() {    $this->middleware('auth');    $this->middleware('log', ['only' => [      'fooAction',      'barAction'    ]]);    $this->middleware('subscribed', ['except' => [      'fooAction',      'barAction'    ]]);  }}
RESTful resource controller

Resource controllers allow you to quickly build RESTful controllers. You can use the artisan command to quickly create an instance:

php artisan make:controller PhotoController --resource

This command will generate the app \ Http \ Controllers \ PhotoController. php file, and the resource controller will contain the corresponding methods for each available resource operation.

You can use the following method to register a resource route:

Route::resource('photo', 'PhotoController');

This simple statement creates multiple routes to process RESTful requests. the resource-based controllers generated by commands also set corresponding processing methods for these requests.

Actions processed by the resource controller
Request method Route address Controller behavior Route Name
GET /Photo Index Photo. index
GET /Photo/create Create Photo. create
POST /Photo Store Photo. store
GET /Photo/{photo} Show Photo. show
GET /Photo/{photo}/edit Edit Photo. edit
PUT/PATCH /Photo/{photo} Update Photo. update
DELETE /Photo/{photo} Destroy Photo. destroy
Some resource routes

Sometimes you may not want the controller to process all the requests, so you can do this:

Route::resource('photo', 'PhotoController', ['only' => [  'index', 'show']]);Route::resource('photo', 'PhotoController', ['except' => [  'create', 'store', 'update', 'destroy']]);
Named resource routing

By default, all resource controller behaviors are named as routes. you can rename them using the names parameter:

Route::resource('photo', 'PhotoController', ['names' => [  'create' => 'photo.build']]);
Named resource routing parameters

By default, the routing parameters of the resource route are named as the corresponding resource name. you can use the parameters parameter to rename it:

Route::resource('user', 'AdminUserController', ['parameters' => [  'user' => 'admin_user']]);// /user/{admin_user}

Sometimes you may want the routing parameters of the resource route to be in the form of a plural number like the default resource name. you can set the parameter to singular by passing the parameters option:

Route::resource('users.photos', 'PhotoController', [  'parameters' => 'singular']);// /users/{user}/photos/{photo}

In addition, you can set your resource routing parameters to the singular form or globally map resource routing parameters:

Route::singularResourceParameters();Route::resourceParameters([  'user' => 'person',  'photo' => 'image'])

When you customize the resource routing parameters, you should clearly know the order priority of naming:

  1. The parameter is directly passed to Route: resource.
  2. Global parameter ING through Router: resourceParameters
  3. Pass the parameter array options to Route: resource or use Route: singularResoureParameters to set parameters in the singular form.
  4. Default behavior
Unexpected behavior in the resource controller

If you must add additional actions to the resource controller to register the corresponding routes, you must register the routes before using Route: resource, otherwise, this behavior may be accidentally overwritten by the resource controller.

Route::get('photos/popular', 'PhotoController@method');Route::resource('photos', 'PhotoController');
Dependency Injection & Controller constructor injection

Laravel service containers support the resolution of all laravel controllers. For this reason, you can add the corresponding type prompts you need in the controller constructor. these dependencies will be automatically parsed and injected into the controller instance.

 users = $users;  }}

Of course, you are also allowed to add some laravel contract type prompts, as long as the service container can be correctly parsed, you can be allowed to add.

Method injection

In addition to dependency injection in Constructors, you can also perform dependency injection in the controller's behavior methods. for example, you can inject the Illuminate \ Http \ Reqeust instance into the controller's store method:

 input('name');  }}

If your controller method also receives parameters transmitted from the route, they will be passed after other dependencies are parsed. for example, your route is defined as follows:

Route::put('user/{id}', 'UserController@update');

Then you can modify your controller behavior to receive parameters:

 Cache route
 
 

Note: cache routes do not support closure function-defined routes. if you want to cache your routes, you should use controllers to manage your routes.

If all your routes are controller-based routes, you should use the cache route recommended by laravel. you can simply use the artisan command to cache all the routes and register them in the same file, it replaces routes. the PHP file is parsed. in some cases, the time for registering a route using this cache method is greatly reduced, thus improving the application response speed. But each time you add or delete a new route, you need to generate a new cache route for the route to take effect:

php artisan route:cache

You can delete the route cache in the following ways:

php artisan route:clear

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.