Laravel Resource Controllers

Laravel resource routing assigns the “CRUD” routes to a controller with the help of single line code.

For E.g.,

If we wish to create a controller that handles all HTTP requests “photos” stored by our application using the make:controller Artisan command. We can quickly create a controller.

php artisan make:controller PhotoController --resource

This above command will generate a controller at

app/Http/Controllers/PhotoController.php.

For each of the available resource operations, the controller will contain a method.

In the next step, we are going to register an original route to the controller:

Route::resource(‘photos’,‘PhotoController’);

The single route declaration creates many routes to handle different types of action on the resource. The generated controller will already have methods for these actions, including notes informing us to the HTTP verbs and URIs they handle.

We register many resource controllers at once by passing an array to the resource method:

Route::resource([
‘photos’ => ‘PhotoController’, 
‘posts’ => ‘PostController’
 ]); 

Actions Handled By Resource Controller

Verb URI Action Route Name
GET /photos index photos.index
GET /photos/create create photos.create
POST /photos store photos.store
GET /photos/{photo} show  photos.show
GET /photos/{photo}/edit edit photos.edit
PUT/PATCH /photos/{photo} update photos.update
DELETE /photo/{photo} destroy photos.destory

Specifying the Resource Model:

If we are using route model binding and would like the resource controller`s methods to type-hint a model instance, we use the --model option when generating the controller:

php artisan make:controller PhotoController   --resource --model=Photo 

Spoofing Form Methods:

Since the HTML forms can`t make PUT, PATCH, or DELETE requests, we will need to add a hidden _method field to spoof these HTTP verbs. The @method Blade directive can create this field for us:

<form action=”/foo/bar” method=”POST”>
 @method(‘PUT’) 
 </form> 
laravel resource controllers

The Resource Controllers are divided into 5 different types:

Partial Resource Route

When declaring a resource route, we specify a subset of actions.

The controller should handle instead of the face set of default actions:

Route::resource( ‘photos’,‘PhotoController’) ->only
([ 
‘index’, ‘show’ 
]); 
Route::resource( ‘photos’, ‘PhotoController’)-> except  
([
‘create’, ‘store’, ‘update’, ‘destroy’  
]); 

API Resource Routes:

When declaring resource routes that will be consumed by APIs, we will commonly want to exclude routes which present HTML templates like create and edit.

We use the apiResource method to exclude these two routes automatically:

Route::apiResource('photos','PhotoController');

We register many API resource controllers at once by passing an array to the apiResources method:

Route::apiResources([
'photos' => 'PhotoController', 
'posts' => 'PostController'
 ]); 

For quickly generate an API resource controller which does not include the create or edit methods, we use the --api switch for executing the make:controller command:

phpartisan make:controller API/PhotoController --api

Naming Resource Routes

By default, all type of resource controller actions have a route name. We can override these names by passing a names array with our options:

Route::resource(‘photos’,‘PhotoController’)->names
([
‘create’ => ‘photos.build’
]); 

Naming Resource Route Parameters

The Route::resource will create the route parameters for our resource routes based on the “singularized” version of the resource name.

We can easily override this on resource basis by using the parameters method.

The array passed into the parameters method should be an associative array of resource names and parameters routes:

Route::resource(‘users’,‘AdminUserController’)->parameters
([ 
‘users’ => ‘admin_user’ 
 ]); 

The above example generates the following URIs for the resource`s show route:

/users/{admin_user}

Localizing Resource URIs

The Route::resource is used by default; it will create a resource URIs using the English verbs.

If we need to localize the create and edit action verbs, we can use the Route::resourceVerbs method.

It may be done in the boot method of our 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 customized, the resource route registration like Route::resource(‘fotos’, ‘PhotoController’) will produce the following URIs:

/fotos/crear
/fotos/{foto}/editar 

Supplementing Resource Controllers

If we need to add additional routes to a resource controller over the default set of resource routes, we should define these routes before our call to the Route::resource.

Otherwise, the routes defined by the resource method will take the lead over our supplement routes:  

Route::get(‘photos/popular’,‘PhotoController@method’);
Route::resource(‘photos’; ‘PhotoController’); 

Related Topics

Laravel Validation

Laravel provides a different way to validate the application`s incoming data. Laravel base controller class uses a ValidatesRequests that provides an easy method to validate incoming HTTP request with many powerful validation rules. Defining the...

5 minutes read.

Features of Laravel Framework

Top 8 Laravel Features Laravel has a very rich set of features that makes the speed of web development faster. The following features that serve the Laravel`s key points: Bundles: Bundles provide us a Modular Packaging...

2 minutes read.

Laravel Creating Views

Creating Views Views hold the HTML served by our application, and it separates our controller/application logic with the help of presentation logic. Views are stored inside the resources/views directory. A simple view...

2 minutes read.

Laravel vs Other Frameworks

Laravel is one of the top listing PHP framework. Some of the reasons which make Laravel top listing PHP framework that are as follows: Authorization Technique.Object-Oriented Libraries.Artisan.MVC Support.Security.Database Migration.Database Template Engine. In this Pie Chart distribution, we...

6 minutes read.

Laravel Eloquent Database Relationships

Eloquent Relationships Laravel: Database tables are related to one another. Eloquent manages and work with easy relationships. It supports some different types of relationship, which are as follows: One to oneOne to manyMany...

8 minutes read.

Laravel Named Routes

Named Routes Named routes allow the suitable generation of URLs or redirects to specific routes. We specify a name for a route by changing the name method onto the route definition: Syntax:  Route::get(‘user/profile’, function () {...

2 minutes read.

Laravel Data Views

Passing the Data Views The data should be an array with the key/value pairs while passing the information in the following (return view(‘greeting’, [‘name’ => ‘John’]);) manner. Inside the view, we...

4 minutes read.

How to Install Git on Windows

Git Installation Git is a distributed version control system. It is used for tracking changes in source code during development. The goals include speed, data integrity, non-linear workflows, etc. Git was developed in 2005. It is free...

3 minutes read.

XAMPP Installation

install xampp on windows XAMPP is a free & open-source stack package which is developed by Apache, mainly it consists of Apache HTTP server, Maria DB database for scripts written in the...

2 minutes read.

Database Migrations

Database Migrations in Laravel Introduction Migrations are version control for our database. It allows our team to modify and share the application`s database. Migrations are paired with schema builder to build an application`s database...

2 minutes read.

Laravel History and Versions

Laravel History Taylor Otwell created the Laravel; it was created as an attempt to provide an advanced alternative to the CodeIgniter framework. The CodeIgniter does not provide several features such as built-in support for...

3 minutes read.

Laravel Advantages

Top 8 Advantages of Laravel The following advantages that Laravel offers, it is based upon designing a web application:- 1. Powerful Authentication: The Laravel PHP framework was developed with a purpose that can help...

2 minutes read.

Laravel Displaying Data

Display data that is passed to our Blade views by enclosing the variable in curly braces. The following route is given below: Route::get('greeting', function () { return view('welcome', ['name' => 'rafia']); }); We display...

2 minutes read.

Laravel Route Parameters

Required Parameters: We need to capture segments of the URI within our route. We are going to see how to pass parameters through two or many views inside the closure function. Route::get('/home',...

2 minutes read.

Laravel Basic Controllers

Controllers group relate request handling logic into a single class. They are stored in the app/Http/Controllers directory. Basic Controllers Defining Controllers: The controllers extend the base controller class included with Laravel. The base class...

2 minutes read.

Laravel Templating Inheritance

Introduction: The Blade is a PHP Templating Engine. It grabs the PHP code and makes it easy for us to implement in HTML. The Blade is a simple, and powerful Templating Engine provided by...

4 minutes read.

Laravel Control Statements

Blade also provides convenient shortcuts for common control structure in PHP, such as conditional statements and loops. These shortcuts provide a very clean working with PHP structures, while also remain familiar to...

3 minutes read.

Laravel Authentication

Authentication is a process of identifying user credentials. Laravel makes implementing authentication very simple. The authentication configuration file is located at config/auth.php that contains various documented options for adjusting the behavior of the authentication...

4 minutes read.

Laravel Forms

CSRF Field For defining an HTML form in our application, we should include a hidden CSRF token field in the form, so that the CSRF protection middleware can validate the request. We use the...

3 minutes read.

Laravel First Packages

First Packages  Laravel provides the following ready to use packages: Cashier: It was introduced in Laravel 4.2 version, it provides an interface for managing subscription billing service, like handling coupons and generating invoices. SSH: It was...

2 minutes read.