LV Laravel Framework

Learn Laravel routing, controllers, Blade, Eloquent, validation, auth, queues, APIs, testing, and deployment.

Lessons

Sign in to save progress
1 Laravel Tutorial 2 Laravel HOME 3 Laravel Introduction 4 Laravel MVC 5 Laravel Installation 6 Composer with Laravel 7 Laravel Project Structure 8 Laravel Artisan 9 Laravel .env Configuration 10 Laravel App Key 11 Laravel Configuration Files 12 Laravel Request Lifecycle 13 Laravel Service Container Intro 14 Laravel Routing Basics 15 Laravel Route Methods 16 Laravel Route Parameters 17 Laravel Named Routes 18 Laravel Route Groups 19 Laravel Route Model Binding 20 Laravel Fallback Routes 21 Laravel Rate Limiting Routes 22 Laravel Controllers 23 Laravel Resource Controllers 24 Laravel Single Action Controllers 25 Controller Dependency Injection 26 Laravel HTTP Requests 27 Laravel Request Input 28 Laravel Responses 29 Laravel Redirects 30 Laravel Middleware 31 Laravel Custom Middleware 32 Laravel Sessions 33 Laravel Cookies 34 Laravel CSRF Protection 35 Laravel Blade Basics 36 Laravel Blade Layouts 37 Laravel Blade Components 38 Laravel Blade Slots 39 Laravel Blade Directives 40 Laravel Blade Loops & Conditionals 41 Laravel Blade Forms 42 Laravel Vite Assets 43 Laravel Frontend CSS/JS 44 Laravel Localization 45 Laravel Validation Basics 46 Laravel Form Requests 47 Custom Validation Rules 48 Validation Messages 49 Old Input & Error Bags 50 Laravel File Uploads 51 Laravel Storage 52 Filesystem Disks 53 Database Configuration 54 Laravel Migrations 55 Laravel Schema Builder 56 Migration Indexes & Constraints 57 Laravel Seeders 58 Laravel Model Factories 59 Database Transactions 60 Laravel Query Builder 61 Laravel Pagination 62 Laravel Collections 63 Eloquent Models 64 Eloquent CRUD 65 Mass Assignment 66 Attribute Casting 67 Accessors & Mutators 68 Query Scopes 69 Soft Deletes 70 Model Events 71 Eloquent Relationships 72 Belongs To Relationships 73 Has Many Relationships 74 Many To Many Relationships 75 Has One Through Relationships 76 Polymorphic Relationships 77 Eager Loading 78 Authentication Overview 79 Laravel Auth Starter Kits 80 Password Hashing 81 Password Reset 82 Email Verification 83 Authorization Gates 84 Authorization Policies 85 Roles & Permissions 86 Laravel Sanctum Basics 87 Laravel API Routing 88 JSON Resources 89 API Validation 90 API Pagination 91 Laravel CORS 92 API Rate Limits 93 Laravel Cache Basics 94 Laravel Cache Tags 95 Laravel Queues 96 Laravel Jobs 97 Failed Jobs 98 Events & Listeners 99 Laravel Mail 100 Laravel Notifications 101 Laravel Broadcasting 102 Task Scheduling 103 Service Container 104 Service Providers 105 Laravel Facades 106 Laravel Contracts 107 Laravel Helpers 108 Laravel Packages 109 Laravel Logging 110 Laravel Error Handling 111 Laravel Exceptions 112 Laravel Testing Basics 113 Laravel Feature Tests 114 Laravel Unit Tests 115 Database Testing 116 HTTP Tests 117 Laravel Mocking 118 Laravel Dusk Overview 119 Telescope & Debugging 120 Laravel Performance 121 Laravel Security Checklist 122 Laravel Deployment 123 Production Environment 124 Config & Route Cache 125 Queue Workers in Production 126 Storage Link 127 Zero-Downtime Deploys 128 Laravel Examples 129 Laravel Quiz 130 Laravel Exercises 131 Laravel Practice Problems 132 Laravel Syllabus 133 Laravel Study Plan 134 Laravel Bootcamp 135 Laravel Interview Prep 136 Laravel Certificate

Laravel Resource Controllers

Laravel Framework Lesson 23 of 136 ~12 min read

Overview

Use REST-style controller methods for index, create, store, show, edit, update, and destroy.

Laravel Resource Controllers is part of Laravel's PHP framework workflow. Laravel gives you expressive routing, controllers, Blade templates, Eloquent models, validation, middleware, queues, testing tools, and deployment conventions so you can build full web applications faster.

Core Ideas

  • Use Laravel Resource Controllers to understand how Laravel moves from route to controller, model, view, response, and tests.
  • Prefer Laravel conventions before inventing custom structure.
  • Use validation, policies, middleware, migrations, and Eloquent relationships deliberately.
  • Keep controllers focused and move reusable work into requests, services, jobs, models, or policies.

Step by Step

  1. Start Laravel Resource Controllers by identifying the route and the HTTP method.
  2. Move request handling into a controller or invokable action.
  3. Validate input before touching Eloquent models or application services.
  4. Return a Blade view, redirect, JSON resource, queued job, or tested response deliberately.

Beginner Explanation

Laravel Resource Controllers controls how browser or API requests reach your application code.

Routes match a URL and HTTP method, then call a controller, closure, or invokable action.

Beginners should start with named routes and focused controllers so links, redirects, tests, and refactors stay clear.

Before You Start

  • Before practicing Laravel Resource Controllers, run php artisan about or php artisan --version so you know the app is booting.
  • Confirm your .env values are for local development and APP_DEBUG is appropriate for your environment.
  • Use php artisan route:list when working on routes, controllers, middleware, or APIs.
  • Use migrations and seeders for database practice instead of editing production data by hand.
  • Keep one tiny feature goal in mind: input, validation, action, response, and test idea.

Key Laravel Concepts

  • routes/web.php is usually for browser routes with sessions and CSRF.
  • routes/api.php is usually for stateless JSON endpoints.
  • Named routes make links and redirects easier to change later.
  • Controllers coordinate a request but should not hold every business rule.

Plain-English Glossary

  • Route: a URL and HTTP method mapped to application code.
  • Controller: a class that coordinates a request and returns a response.
  • Middleware: code that runs before or after the request handler.
  • Blade: Laravel template syntax for server-rendered HTML.
  • Migration: a version-controlled database schema change.
  • Eloquent model: a PHP class representing a database table.
  • Policy: a class that decides whether a user can perform an action.
  • Service container: Laravel system for resolving class dependencies.

What You Will Learn

  • Explain where Laravel Resource Controllers belongs in the Laravel request lifecycle.
  • Name the main file or command you would use for this topic.
  • Write a small Laravel example that follows framework conventions.
  • Identify one validation, authorization, performance, or deployment risk for the topic.

Where You Use This in Real Projects

You use Laravel Resource Controllers in dashboards, admin panels, blogs, shops, APIs, CMS features, auth systems, imports, exports, reports, notifications, and deployment pipelines.

Laravel is productive because common web tasks have clear framework homes, but good structure still depends on small controllers, safe models, clear validation, and tests.

A reliable Laravel workflow is: define the route, validate input, authorize the action, call a model or service, return a view or JSON resource, and add a focused test.

Laravel Safety Notes

  • Validate request data before saving or using it.
  • Use Blade escaped output for user-controlled content.
  • Protect model mass assignment with fillable or guarded fields.
  • Use policies, gates, middleware, CSRF protection, hashed passwords, and environment variables for sensitive behavior.
  • Check logs and tests before deploying changes that touch auth, payments, files, queues, or database migrations.

Beginner Mental Model

Think of Laravel Resource Controllers as one part of Laravel's route-to-response pipeline.

The router decides what code runs, middleware filters the request, controllers coordinate work, models talk to data, and Blade or resources shape the response.

When a feature becomes hard to read, ask which Laravel layer should own each responsibility.

Framework Flow

  1. A request for Laravel Resource Controllers enters Laravel through public/index.php and the HTTP kernel.
  2. The router matches the URL and method, then middleware can allow, block, or modify the request.
  3. A controller, invokable action, job, or closure handles the feature and calls validation, models, policies, services, or views.
  4. Laravel returns a response such as a Blade page, redirect, download, JSON resource, or streamed result.

Key Files and Commands

  • routes/web.php and routes/api.php define browser and API routes.
  • app/Http/Controllers contains request handlers.
  • resources/views contains Blade templates and layouts.
  • app/Models and database/migrations describe database-backed data.
  • php artisan route:list, migrate, make:controller, make:model, test, and serve are daily commands.

Security and Project Notes

  • Validate all request input before saving or using it.
  • Use Blade escaping with {{ }} for user content unless you intentionally render trusted HTML.
  • Protect mass assignment with fillable or guarded model properties.
  • Use middleware, policies, gates, hashed passwords, CSRF protection, and environment variables for sensitive configuration.

Code Example

use App\Http\Controllers\LessonController;
use Illuminate\Support\Facades\Route;

Route::middleware('web')->group(function () {
    Route::get('/lessons', [LessonController::class, 'index'])->name('lessons.index');
    Route::post('/lessons', [LessonController::class, 'store'])->name('lessons.store');
});

Another Example

// routes/web.php
Route::get('/lessons/{lesson:slug}', [LessonController::class, 'show'])->name('lessons.show');

// app/Http/Controllers/LessonController.php
public function show(Lesson $lesson)
{
    return view('lessons.show', ['lesson' => $lesson]);
}

More Practice Examples

Example 1: Route to controller

Route::get('/courses', [CourseController::class, 'index'])->name('courses.index');

public function index()
{
    return view('courses.index', [
        'courses' => Course::query()->latest()->paginate(10),
    ]);
}
  • The route is named so views and redirects can reference it safely.
  • The controller returns one response and keeps the query easy to inspect.
  • Pagination prevents loading too many rows at once.

Example 2: Validate and save

$data = $request->validate([
    'title' => ['required', 'string', 'max:120'],
    'body' => ['nullable', 'string'],
]);

$lesson = Lesson::create($data);

return redirect()->route('lessons.show', $lesson)->with('status', 'Lesson created.');
  • Validation runs before data is saved.
  • Mass assignment requires matching fillable fields on the model.
  • Redirects after POST help avoid duplicate form submissions.

Example 3: Test the behavior

$this->post('/lessons', [
    'title' => 'Laravel Practice',
    'slug' => 'laravel-practice',
])
    ->assertRedirect()
    ->assertSessionHasNoErrors();

$this->assertDatabaseHas('lessons', ['slug' => 'laravel-practice']);
  • The test checks the HTTP result and the database result.
  • Session assertions catch validation mistakes.
  • Database assertions verify that the feature really saved data.

Real-World Feature Pattern

Route::post('/lessons', [LessonController::class, 'store'])->name('lessons.store');

public function store(StoreLessonRequest $request)
{
    $this->authorize('create', Lesson::class);

    $lesson = Lesson::create($request->validated());

    PublishLessonDraftJob::dispatch($lesson);

    return redirect()
        ->route('lessons.show', $lesson)
        ->with('status', 'Lesson saved.');
}
  • This Laravel Resource Controllers pattern shows the Laravel habit of splitting route, validation, authorization, model work, queued work, and response.
  • The controller coordinates the feature but does not define every rule inline.
  • The redirect and flash message create a clean browser workflow after a successful POST.

Example Explained

  • The Laravel Resource Controllers example follows Laravel conventions so another developer can find the route, controller, model, view, and test.
  • The public entry point is the route, not the controller file itself.
  • Validation and authorization happen before records are changed.
  • Models, resources, views, jobs, or services do the focused work after the controller coordinates the request.
  • The final line returns a response the browser or API client can understand.

How to Read This Example

  1. Start with the route so you know the URL, method, middleware, and name.
  2. Read the controller method to see the request inputs and returned response.
  3. Find validation and authorization before database writes.
  4. Check model fillable fields, relationships, casts, and queries when data is involved.
  5. For Laravel Resource Controllers, change one Laravel layer at a time and rerun the route or test.

Checklist

  • Use routes, controllers, form requests, models, migrations, and policies in their intended roles.
  • Protect mass assignment, validate input, escape output, and keep secrets in environment config.
  • Write at least one feature test for important request flows.

Common Mistakes

  • Putting all business logic directly inside controllers.
  • Skipping request validation because Eloquent makes saving data easy.
  • Ignoring policies, middleware, mass-assignment rules, queues, and environment configuration.

Do and Don't

  • Do: practice Laravel Resource Controllers with a tiny route-to-response feature.
  • Do: use Laravel conventions for file locations, class names, route names, validation, and tests.
  • Do: validate input, authorize actions, escape output, protect mass assignment, and check logs.
  • Don't: put all business logic, queries, validation, and HTML into one controller method.
  • Don't: deploy with APP_DEBUG=true, missing APP_KEY, public secrets, or untested migrations.

Practice Challenge

Create a small Laravel note, product, or lesson feature for Laravel Resource Controllers. Write the route, controller logic, validation, model or migration, view or JSON response, and one test idea.

Try These Changes

  • Add a named route and generate its URL from a Blade view.
  • Move inline validation into a Form Request class.
  • Add a policy check before changing a model.
  • Write one feature test for the success path and one validation failure.
  • For Laravel Resource Controllers, identify which Laravel file owns each part of the feature.

Quick Check

  • Question: What file is usually the first public entry point? Answer: public/index.php.
  • Question: What command lists routes? Answer: php artisan route:list.
  • Question: Why use Form Requests? Answer: To keep validation and authorization rules reusable and focused.
  • Question: Why protect fillable fields? Answer: To prevent unsafe mass assignment.
  • Question: What should Laravel Resource Controllers return? Answer: A clear response such as a view, redirect, JSON resource, download, or error.

Debugging Checks

  • Run php artisan route:list to confirm the URL, method, middleware, and controller.
  • Check storage/logs/laravel.log for the first useful exception message.
  • Confirm .env values for APP_KEY, APP_ENV, APP_DEBUG, database, cache, queue, mail, and session settings.
  • Use php artisan optimize:clear when cached config, routes, or views look stale in development.
  • For Laravel Resource Controllers, write a small feature test so the same behavior can be checked again after changes.

Mini Project

Build a route practice feature for Laravel Resource Controllers: one named GET route, one POST route, one controller method, one redirect, and one route:list check.

Mastery Check

  • You can explain where Laravel Resource Controllers belongs in a Laravel project and why.
  • You can connect a route, controller, request validation, Eloquent model, Blade view, and test.
  • You can choose the right Laravel feature instead of forcing everything into one controller.
Create a free account to save which lessons you've finished. Save my progress