Laravel for Beginners – Learn to Build Full-Stack Web Apps

Loading video...

Basic Controllers

Controllers

Basic Controllers

What is controller?

Controller is a class which is associated to one or more routes and is responsible for handling requests of that routes. Generally controller is for grouping similar routes together. For example: ProductController should contain only logic associated to products, but not anything else. CarController should not contain logic that is not associated to cars.

Generate controller with artisan

php artisan make:controller CarController

CarController.php class was generated in app/Http/Controllers folder. This is the default content of the just generated controller in Laravel 11.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class CarController extends Controller
{
    //
}

Create route and associate action

Now let’s open CarController and add method index, so that our controller looks like this..

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class CarController extends Controller
{
    public function index()
    {
        return "Index method from CarController";
    }
}

Now let’s open routes/web.php file and add new route which will be associated to just created index method.

Route::get("/car", [\App\Http\Controllers\CarController::class, 'index']);

In the exact same way you can define other methods in CarController and associate to new routes.

How let’s access http://127.0.0.1:8000/car into browser and you should see the following output.

Index method from CarController

Discussion

Sign in to join the discussion.

No comments yet. Be the first to start the discussion!