🌟 Laravel Resource Controller and Route With Example – Complete Guide

Laravel, one of the most popular PHP frameworks, provides developers with a robust set of tools to build modern web applications. One of its powerful features is resource controllers, which simplify the way we handle CRUD operations (Create, Read, Update, Delete) for any model or resource in our application.

In this comprehensive guide, we’ll explore:

  • What is a Resource Controller in Laravel?
  • How to create and use resource controllers
  • The routes it generates
  • Practical example with step-by-step implementation
  • Sample views and best practices

Let’s dive into this powerful feature and learn how to master resource controllers in Laravel.


🧠 What is a Resource Controller?

A Resource Controller in Laravel is a special type of controller that comes with a set of predefined methods to handle the CRUD functionality for a resource.

Instead of writing separate routes and controller methods manually for each operation, Laravel provides an Artisan command that automatically generates these methods for you, saving time and maintaining consistency in your codebase.

For example, if you’re managing users in your application, the resource controller will include methods like:

  • index() – Show all users
  • create() – Show form to create a new user
  • store() – Store a newly created user
  • show($id) – Display a specific user
  • edit($id) – Show form to edit a user
  • update($id) – Update a specific user
  • destroy($id) – Delete a user


🚀 Step-by-Step: Implementing Laravel Resource Controller

Let’s walk through a practical example where we build a User Resource Controller from scratch.


✅ Step 1: Create a New Laravel Project

If you don’t already have a Laravel project set up, create a new one using Composer or Laravel Installer:

composer create-project laravel/laravel resource-demo cd resource-demo

Or, using Laravel Installer:

laravel new resource-demo

✅ Step 2: Create a Model and Migration

Let’s generate a model and migration for the User resource (or any other resource you want to manage):

php artisan make:model User -m

Open the migration file in database/migrations/ and define the user table structure:

public function up() { Schema::create('users', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('email')->unique(); $table->timestamps(); }); }

Now run the migration:

php artisan migrate

✅ Step 3: Generate a Resource Controller

Now we generate a resource controller using the --resource flag:

php artisan make:controller UserController --resource

This will create a file at app/Http/Controllers/UserController.php with all 7 resource methods.


✅ Step 4: Define Routes

To map the HTTP routes to your new controller methods, open routes/web.php and use Laravel’s Route::resource:

use App\Http\Controllers\UserController; Route::resource('users', UserController::class);

This single line generates the following routes automatically:

Method URI Action Route Name
GET /users index users.index
GET /users/create create users.create
POST /users store users.store
GET /users/{id} show users.show
GET /users/{id}/edit edit users.edit
PUT/PATCH /users/{id} update users.update
DELETE /users/{id} destroy users.destroy

You can list all your routes using:

php artisan route:list

✅ Step 5: Implement Resource Controller Methods

Now open your UserController.php file and implement the logic. Here’s a basic example:

namespace App\Http\Controllers; use App\Models\User; use Illuminate\Http\Request; class UserController extends Controller { public function index() { $users = User::all(); return view('users.index', compact('users')); } public function create() { return view('users.create'); } public function store(Request $request) { $request->validate([ 'name' => 'required', 'email' => 'required|email|unique:users' ]); User::create($request->all()); return redirect()->route('users.index')->with('success', 'User created successfully.'); } public function show(User $user) { return view('users.show', compact('user')); } public function edit(User $user) { return view('users.edit', compact('user')); } public function update(Request $request, User $user) { $request->validate([ 'name' => 'required', 'email' => 'required|email|unique:users,email,'.$user->id ]); $user->update($request->all()); return redirect()->route('users.index')->with('success', 'User updated successfully.'); } public function destroy(User $user) { $user->delete(); return redirect()->route('users.index')->with('success', 'User deleted successfully.'); } }

💡 Note: Make sure to add fillable attributes in the User model:

protected $fillable = ['name', 'email'];

✅ Step 6: Create Blade Views

Create a folder resources/views/users/ and add the following view files:

📄 index.blade.php

@extends('layout') @section('content') <h1>All Users</h1> <a href="{{ route('users.create') }}">Create New User</a> @foreach($users as $user) <p>{{ $user->name }} - {{ $user->email }}</p> <a href="{{ route('users.show', $user->id) }}">View</a> | <a href="{{ route('users.edit', $user->id) }}">Edit</a> | <form action="{{ route('users.destroy', $user->id) }}" method="POST" style="display:inline;"> @csrf @method('DELETE') <button type="submit">Delete</button> </form> @endforeach @endsection

📄 create.blade.php

@extends('layout') @section('content') <h1>Create User</h1> <form action="{{ route('users.store') }}" method="POST"> @csrf <input type="text" name="name" placeholder="Name" required> <input type="email" name="email" placeholder="Email" required> <button type="submit">Save</button> </form> @endsection

Similarly, create edit.blade.php, show.blade.php, and a base layout.blade.php.


🧪 Step 7: Test It in the Browser

Now start your Laravel server:

php artisan serve

Visit:

  • http://localhost:8000/users – list of users (index)
  • /users/create – create form
  • /users/{id} – single user view
  • /users/{id}/edit – edit form

You’ll now have a fully functioning CRUD app using Laravel resource controllers.


🔍 Advanced Tip: Only Load Needed Routes

If you don’t need all 7 routes, you can customize:

Route::resource('users', UserController::class)->only([
'index', 'create', 'store' ]); Route::resource('users', UserController::class)->except([ 'destroy' ]);

🧩 Summary

Laravel’s Resource Controllers make CRUD operations fast, organized, and maintainable. With just one line of code, you can scaffold multiple routes and corresponding controller methods to manage your application's resources efficiently.

✨ Key Takeaways:

  • Use php artisan make:controller NameController --resource to generate a resource controller.
  • Register it with Route::resource('name', NameController::class);.
  • Use Blade templates to create corresponding views.
  • Extend functionality as needed — Laravel gives you full control.


✅ What Next?

Now that you’ve learned about Laravel resource controllers:

  • Try implementing one for a Product, Category, or Post model.
  • Integrate form validation, file uploads, or authorization.
  • Learn how to use API resource controllers (php artisan make:controller --api).

Laravel makes resource handling incredibly clean and developer-friendly. Mastering this will drastically improve your development speed and code organization.


💬 Have questions or want more Laravel tutorials? Drop a comment or check out From ZeroToDev!

Post a Comment

Previous Post Next Post

Contact Form