This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

📣 Try the fastest hosting platform with pay-as-you-go pricing & 24/7 expert support! MIGRATE NOW →

Working With Controllers and Middleware in Laravel 8.x

Updated on March 8, 2024

8 Min Read
laravel middleware

Laravel Middleware provides a convenient mechanism for assessing and sifting through HTTP demands that enter your application. All of these middleware are found within the app/Http/Middleware registry.

Laravel Middleware acts as a bridge between a request and a reaction. It is a type of sifting component. Laravel incorporates a middleware that confirms whether or not the client of the application is verified. If the client is confirmed, it diverts to the home page otherwise, it diverts to the login page.

All controllers in Laravel are created in the Controllers folder, located in App/Http/Controllers. All controllers must have the namespace `App\Http\Controllers` and extends from the Controller class.

What Are Controllers in Laravel

Controllers help in maintaining a separation of concerns by encapsulating the request handling logic separate from the routes and views. This enhances the code’s readability, maintainability, and scalability. Controllers in Laravel are typically stored in the app/Http/Controllers directory and follow a specific naming convention.

Basic Controllers

Basic controllers in Laravel are classes that contain methods to handle various HTTP requests. These controllers typically group related request handling logic together. Each method within a controller corresponds to a specific route or endpoint in the application.

Basic controllers often utilize methods like index(), show(), store(), update(), and destroy() to handle CRUD (Create, Read, Update, Delete) operations for resources.

Here is an example of how you can use basic controllers to manage your classes and HTTP requests.

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function index()
    {
        // Logic to fetch and display a list of users
    }
    public function show($id)
    {
        // Logic to fetch and display a specific user
    }
    public function store(Request $request)
    {
        // Logic to store a new user
    }
    // Other methods like update() and destroy() would be defined here
}

Single Action Controllers

Single-action controllers are an alternative to traditional controllers when you only need a single action within the controller. Instead of defining multiple methods, you define a single __invoke() method within the controller class.

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class WelcomeController extends Controller
{
    public function __invoke()
    {
        return view('welcome');
    }
}

Experience Seamless Laravel Hosting on Cloudways!

Elevate Your Laravel Development and unlock the full potential of Laravel with Cloudways hosting.

How to Create a Basic Controller in Laravel

Remember the tables example in the article on routing.

I will now create a controller using a single method which will print the required table on the screen. To define a controller in Laravel, first give it a name. In this example, I will name the controller Table and then add Controller to the name. The full name of the controller class is now TableController. Remember that all the controllers in Laravel must have the word Controller at the end.

You can create controllers in two ways:

  • Manually create a file
  • Use Artisan to create the controller (this is the easy option!)

I will now demonstrate how you could create a controller using the Laravel Artisan command. I will use the following command:

php artisan make:controller TableController

Once the command is completed, an empty `TableController` class will be generated in the Controllers folder with name `TableController.php`. At this point, the class looks like:

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
class TableController extends Controller
{

   //

}

I will now add the logic for generating the table. Create a new method `create` inside `TableController`:

public function create($number = 2)
{
    for($i =1; $i <= 10 ; $i++){
        echo "$i * $number = ". $i* $number ."<br>";
    }
}

This is the same logic that I used in the rout (refer to the article on Laravel routes). I will now remove this functionality from the route and then bind the controller to it

Route::get('/table/{number?}', 'TableController@create')→where('number', '[0-9]+');

Now whenever the URL is executed, the control action `create` will be called and the table for the number would be generated.

How to Create a Resource Controller

Resource controllers are used to create CRUD options for routes.

Let’s say, I have a model for Books, and now I want to create a controller that will perform its CRUD methods for the route in the controller. Laravel provides an easy way of doing this. Using a single command, I can create a resource controller and define a Model with it (another great feature of Laravel).

I will use the following command for creating a resource controller:

php artisan make:controller BookController --resource

Once the command is executed, you will be asked to create the Book model since it does not exists at the moment. Type yes for now and hit Enter. Once it finishes, a `BookController` will be created along with the model binded in it. You will get the following actions in the `BookController`:

  • index() → To view all Book lists
  • create() → To load a view to create a new book
  • store(Request $request) → To save the newly created book
  • show($id) → To view a single book
  • edit($id) → To load a view for editing
  • update(Request $request, $id) → To update a single book
  • destroy($id) → To delete a book

Model binding is important because it reduces the lines of code and streamlines the overall design of the application. Take the example of getting a book by its id. When not using model binding, I would require the following steps to find the book details through the id.

Route::resource('book', 'BookController');

This single declaration will create several routes to handle BooksController requests. The resource route will handle the following actions:

Stop Wasting Time on Servers

Cloudways handle server management for you so you can focus on creating great apps and keeping your clients happy.

VerbURIActionRoute Name

GET /books index books.index
GET /books/create create books.create
POST /books store books.store
GET /books/{book} show books.show
GET /books/{book}/edit edit books.edit
PUT/PATCH /books/{book} update books.update
DELETE /books/{book} destroy books.destroy

You can also specify a resource route to handle only certain actions or can exclude the actions that you do not want a route to handle. Here is the syntax of the code snippets for both the situations:.

Route::resource('book', 'BookController', ['only' => [

   'index', 'show'

]]);

Route::resource('book', 'BookController', ['except' => [

   'create', 'store', 'update', 'destroy'

]]);

Once you save the file, only the following routes will be handled:

Controller-Model Binding in Laravel

With Laravel, you can now bind a model(s) to your resource controller by adding `-model=modelname` to the Artisan command.

php artisan make:controller BookController --resource --model=Book

When you run this command, the following functions will be binded to controllers.

  • show(Book $book) → view a single book
  • edit(Book $book) → load a view for editing
  • update(Request $request, Book $book) → update a single book
  • destroy(Book $book) → delete a book

Model binding is important because it reduces the lines of code and streamline the overall design of the application. Take the example of getting a book by its id. When not using model binding, I would require the following steps to find the book details through the id.

public function show($id)
{
    $book = Book::where('id', $id)->get();
    return view('book.book',['book’ => $book]);
}

Now, with model binding, I only have to return the view of that Book and all the rest, i.e. finding the book by the id and error generation will be done by Laravel itself.

public function show(Book $book)
{
    return view('book.book',['book' => $book]);
}

As you could see in this example, I have managed to reduce one line of code. In larger projects, this advantage would become more apparent!.

This is it for controllers. You can learn more about resource routing in Laravel in the official documentation. I will now discuss Middlewares in Laravel.

What Are Middleware in Laravel and How to Create Them?

Middleware are the easiest way of verifying HTTP requests before they are passed to the controller. All middleware in Laravel are created in the Middleware folder, located inside the `app/HTTP` folder.

Creating a Basic Middleware in Laravel

The process of creating a middleware is very similar in both Laravel 8 or any Laravel higher version.

I will now create a middleware for our Books controller in which the books that correspond to a particular year will not be stored in the database. I will name this middleware CheckYear and use the following Artisan command:

php artisan make:middleware CheckYear

Once the command is finished a middleware will be create with a handle function (to which I will add the logic).

<?php

namespace App\Http\Middleware;

use Closure;

class CheckYear

{

   /**

    * Handle an incoming request.

    *

    * @param  \Illuminate\Http\Request  $request

    * @param  \Closure  $next

    * @return mixed

    */

   public function handle($request, Closure $next)

   {

       $year = ['1956','1970','1972'];

       if (array_has($year,$request->year)) {

           return redirect('home');

       }

       return $next($request);

   }

}

In the above code, I defined the array $year, in which I added the years that I do not want to add to the database. Next, I used the Laravel helpers function array_has to check the input for the year requested. If the year exists in the array, it will be redirected to home. Otherwise, the request will be completed.

Now that I have a middleware, I will now define a controller. The easiest way to define the middleware is in the constructor of the controller. Remember to define the namespace of the middleware in the controller as well. See the following code for defining the middleware in the constructor:

<?php

namespace App\Http\Controllers;

use App\Book;

use Illuminate\Http\Request;

use App\Http\Middleware\CheckYear;

class BookController extends Controller

{

   /**

    * Constructor.

    *

    * @return void

    */

   public function __construct()

   {

       $this->middleware(CheckYear::class);

   }

You can define the middleware in `app/Http/Kernel.php` file, in  `$routemiddleware` array and assign a key to it. Check out the following code:

protected $routeMiddleware = [

       'auth' => \Illuminate\Auth\Middleware\Authenticate::class,

       'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,

       'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,

       'can' => \Illuminate\Auth\Middleware\Authorize::class,

       'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,

       'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,

       'year' => \App\Http\Middleware\CheckYear::class

   ];

This way, I do not need to define the middleware class in the controller. I could just call it by its name (see the following code):

<?php

namespace App\Http\Controllers;

use App\Book;

use Illuminate\Http\Request;

class BookController extends Controller

{

   /**

    * Constructor.

    *

    * @return void

    */

   public function __construct()

   {

       $this->middleware(‘year’);

   }

In addition, you can define the middleware directly to the routes too.Just add the route directly!

Route::post('/books',’BooksController@store’)->middleware('year');

Route::put('/books/{book}',’BooksController@update’)->middleware('year');

Create a Middleware for Controller Without a Separate Class

In a controller, you can define a middleware without writing a separate class for it. The code for the middleware  and the constructor is:

<?php

namespace App\Http\Controllers;

use App\Book;

use Illuminate\Http\Request;

class BookController extends Controller

{

   /**

    * Constructor.

    *

    * @return void

    */

   public function __construct()

   {

       $this->middleware(function($request,$next)

       {

           $year = ['1956','1970','1972'];

           if (array_has($year,$request->year)) {

               return redirect('home');

           }

           return $next($request);

       });

   }

 

This will work as if you have created a separate class for the middleware. Check out the official documentation for more information on middlewares. Now, it will be as if you have created a separate class for it. You can learn more about middleware in Laravel from the official documentation.

Power Your Laravel Projects with Cloudways Hosting – Fast, Secure, and Scalable!

Supercharge Your Laravel Projects with Cloudways Hosting! Deploy Now for Lightning-Fast Performance and Unbeatable Reliability!

Conclusion

In this tutorial, I offered an overview of controllers and middleware in Laravel, discussed how to create simple and resource controllers, and how to define their routes. I also discussed how to create simple middleware and how to bind them to controllers and routes. If you wish to add a suggestion or have any questions, do leave a comment below

Q: What is middleware in Laravel controller?

A: Middleware in Laravel controllers acts as a filter for HTTP requests, allowing you to intercept and modify incoming requests before they reach the controller’s action.

Q: Can we use middleware in controller?

Yes, middleware can be used in Laravel controllers. By attaching middleware to specific controller routes or controller actions.

Q: What is the difference between controller and middleware?

A: Controllers in Laravel handle the application’s HTTP requests, containing the logic to process and respond to incoming requests.
Whereas, middleware acts as a filter for these requests, intercepting them before they reach the controller, enabling tasks such as authentication, validation, and request modification.

Q. What is a Laravel controller and what is the use of controllers in Laravel?

A: In a Laravel project, controller classes are associated with a resource (URI). They handle all logic related to a particular URI (such as a blog). Laravel controllers separate logic from the rest of the code so you can safely change the code without disrupting the views.

Q: How do I add a controller in Laravel?

A: In Laravel, you can add a Controller by using the Artisan command:

php artisan make:controller

This will create the controller in the app/Http/Controllers directory.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Shahzeb Ahmed

Shahzeb is a Digital Marketer with a Software Engineering background, works as a Community Manager — PHP Community at Cloudways. He is growth ambitious and aims to learn & share information about PHP & Laravel Development through practice and experimentation. He loves to travel and explore new ideas whenever he finds time. Get in touch with him at [email protected]

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

CYBER WEEK SAVINGS

  • 0

    Days

  • 0

    Hours

  • 0

    Mints

  • 0

    Sec

GET OFFER

For 4 Months &
40 Free Migrations

For 4 Months &
40 Free Migrations

Upgrade Now