Good content takes time and effort to come up with.

Please consider supporting us by just disabling your AD BLOCKER and reloading this page again.







What Is Laravel Resourceful Controllers?


RESOURCEFUL CONTROLLERS SLIM CONTROLLERS PHP PHP LARAVEL LARAVEL
05th May 2020 4 mins read
Share Article     Share On WhatsApp   Buy Me Coffee | StackCoder Buy Coffee


Vaṇakkam! In this article your will learn all about Laravel resourceful controllers & its advantages of using in your daily life for development process.


I will make a fresh Laravel project and create Products CRUD operations with it. At the end of the article you will find the link to GitHub repository.
NOTE: I will be coding only the Controller & Routing side. There wont be any frontend code. But yes! based on the requests in GitHub repository I will create one.

Prerequisites


Laravel installed in your computer or server. To install Laravel you can use the following


composer create-project --prefer-dist laravel/laravel invoice

Why Laravel Resourceful Controllers?


Most of the time in your development process you will be creating CRUD operations and it may take up some time to do so because you need to create CRUD functions in Controllers and Web Routes in web.php file


This is all simplified in Laravel with single line of artisan command & one line code in web.php


Creating Resourceful Products Controller & Models & Migrations


New Resourceful Controller, Models & Migrations


Since I am very lazy I would like to create the Model, Migration, Controller, Resourceful Controller with one single command as follows:


php artisan make:model Models/Product --controller --migration --resource


No need to use optional parameters with the lengthy names, you can use alias as following. Just for the sake of demonstration I showed you that way.


--controller -> -c

--migration -> -m

--resource -> -r


TIP: If I am working on small project I will keep all my models in one single folder called as Models.
If any big projects now days I am more fascinated towards Repository Pattern, but its totally upto your choice.

Resourceful Controller Only


If you already have Model & Migration then use the following command just to create the resourceful controller.


php artisan make:controller ProductsController --model="Models/Product" --resource


TIP: If you pass --model then Laravel will autogenerate Route Model Binding for that model. Awesome right?

Resourceful Routes in web.php


Auto Resourceful Routes


Instead of typing all the routes you can just add single line of code in web.php ie resourceful route as follows


web.php


Route::resource('products', 'ProductsController');


Yes thats it. If you want to know what are all the URLS's that is registered then use the route:list command as follows


php artisan route:list


You will be able to see the following routes. Don't worry I have selected only 3 columns with the following command


php artisan route:list --columns=Method,URI,Action


+-----------+-------------------------+-------------------------------------------------+
| Method    | URI                     | Action                                          |
+-----------+-------------------------+-------------------------------------------------+
| GET|HEAD  | products                | App\Http\Controllers\ProductsController@index   |
| POST      | products                | App\Http\Controllers\ProductsController@store   |
| GET|HEAD  | products/create         | App\Http\Controllers\ProductsController@create  |
| GET|HEAD  | products/{product}      | App\Http\Controllers\ProductsController@show    |
| PUT|PATCH | products/{product}      | App\Http\Controllers\ProductsController@update  |
| DELETE    | products/{product}      | App\Http\Controllers\ProductsController@destroy |
| GET|HEAD  | products/{product}/edit | App\Http\Controllers\ProductsController@edit    |
+-----------+-------------------------+-------------------------------------------------+

Manual Routes


If you are still not convinced and were to add it manually then you should add the following in web.php


web.php


Route::get('/products', 'ProductsController@index');
Route::get('/products/create', 'ProductsController@create');
Route::post('/products', 'ProductsController@store');
Route::get('/products/{product}', 'ProductsController@show');
Route::get('/products/{product}/edit', 'ProductsController@edit');
Route::patch('/products/{product}', 'ProductsController@update');
Route::delete('/products/{product}', 'ProductsController@destroy');

Overall Controller (Birds Eye View)


Overall you controller will look like the following


<?php

namespace App\Http\Controllers;

use App\Models\Product;
use Illuminate\Http\Request;
use App\Http\Requests\Products\ProductCreateRequest;
use App\Http\Requests\Products\ProductUpdateRequest;

class ProductsController extends Controller
{
    public function index()
    {
        $product = Product::orderByDesc('created_at')->simplePaginate(10);
        return view('product.index', [
            'products' => $product
        ]);
    }

    public function create()
    {
        return view('product.create');
    }

    public function store(ProductCreateRequest $request)
    {
        Product::addProduct($request->all());
        return redirect('/products');
    }

    public function show(Product $product)
    {
        return view('product.show', [
            'product' => $product
        ]);
    }

    public function edit(Product $product)
    {
        return view('product.edit', [
            'product' => $product
        ]);
    }

    public function update(ProductUpdateRequest $request, Product $product)
    {
        Product::updateProduct($product, $request->all());
        return redirect('/products');
    }

    
    public function destroy(Product $product)
    {
        $product->delete();
        return redirect('/products');
    }
}


Yo! Hold on one second. Where are my validation rules? Those are extracted to Form Requests ProductCreateRequest & ProductUpdateRequest .


If you would like to learn more about the Form Requests then I have written an article on it Make Laravel Controllers Slim By Skimming Form Validation Request


NOTE: Most of the code over here is not written as the main objective of this article was to make you understand about the Resourceful Controllers & Routes

GITHUB Project Link


Use the following link to review the project


Invoice Demo Project


NOTE: This is not a complete project, this is just to demo you how to work with resourceful controllers.

Conclusion


Hope this cleared your doubts.


WHATS NEXT?


You might be interested in reading few of my other articles


Route Model Binding In Laravel & Change Default Column id To Another Column

Make Laravel Controllers Slim By Skimming Form Validation Request


Happy Coding :)








Author Image
AUTHOR

Channaveer Hakari

I am a full-stack developer working at WifiDabba India Pvt Ltd. I started this blog so that I can share my knowledge and enhance my skills with constant learning.

Never stop learning. If you stop learning, you stop growing