Laravel Controller

Last Updated: September 4, 2022

The objective of the Controller:

Capture the request of the user and execute the business logic based on the data of the request

How to create Laravel Controller

In this lesson, we will see how to create your first controller in Laravel. If you do not know how to install Laravel on your computer you can see this tutorial.

This is the directory structure of the Laravel project

Laravel Directory Structure

So you can create your controller App > Http > Controllers

You can run the following command inside the terminal to create Laravel Controller.

php artisan make:controller UserController 

If you want to create a controller with model you can use the following code.

php artisan make:controller UserController --model=User 

Above artisan command will create the following code in App\Http\Controllers namespace.

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller

Now I will create the show() inside the UserController

class UserController extends Controller

    public function show(){
    	echo "User Details";

Now you can define the route for this controller action in routes>web.php file

Route::get('user/{id}', 'UserController@show');

Single Action Controller

Entire controller has only a single action


namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\User;

class ProvisionServer extends Controller
     * Provision a new web server.
     * @return \Illuminate\Http\Response
    public function __invoke()
        // ...

Use the following artisan command to create a Laravel single-action controller

php artisan make:controller ProvisionServer --invokable

Use the following route to access this Laravel single action controller

use App\Http\Controllers\ProvisionServer;

Route::post('/server', ProvisionServer::class);