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.

Working With Controllers and Middleware in Laravel 8.x

Updated on December 27, 2021

7 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.

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?}', '[email protected]')→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.

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 5.5, 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 and Where 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 5.3 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',’[email protected]’)->middleware('year');

Route::put('/books/{book}',’[email protected]’)->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.

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 a Laravel controller?

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).

Q: What is the use of controllers in Laravel?

A: Laravel is an MVC framework and as such controllers perform a similar function as the controllers in similar frameworks. In Laravel projects, 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

Customer Review at

“Cloudways hosting has one of the best customer service and hosting speed”

Sanjit C [Website Developer]

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!