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

1.8K

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

Ahmad Aziz

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 ☕️

Post Tutorials

Learn trending tutorials for ReactJs, React Native, VueJS, NextJs, Laravel, Tailwind CSS, and Flutter development.
View Tutorials

Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that's right for your web projects
View Components

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this