Home / Snippets / Adding Other Method to Resource Controller in Laravel
Adding Other Method to Resource Controller in Laravel cover

Adding Other Method to Resource Controller in Laravel

2.1K

2 years ago

0 comments

To add another method to the resource you can define a new one below the route resource definition on the "routes/web.php" file. For an example, you can see the command below where it's creating a new controller called "ArticleController" and having the "-r" flag which stands for "resource".
php artisan make:controller ArticleController -r
By default it will have all the "index", "create", "store", "show", "edit", "update" and "destroy". Now if you want to add a new method to the existing resource you can define a new method such as the following.
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ArticleController extends Controller
{
    /* Your other codes here */

    public function trending()
    {
        // your code logic here
    }
}
Now from your "routes/web.php" file you can define your route resource as follow.
<?php

Route::resource('articles', \App\Http\Controllers\ArticleController::class);
Route::get('articles/trending', [\App\Http\Controllers\ArticleController::class, 'trending']);
If you want to view all of your routes available from within the application then you can run the route:list command.
php artisan route:list
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this