Create a middleware to secure the data for your Laravel REST APIs

Whether you are working on building a mobile app or an IOT device, chances are you have encountered the need to use REST APIs to communicate data from server to a web-based client.  With most programming languages such as PHP, Ruby, or Python, you can easily use frameworks to develop them for your next project. While some may question its strengths and weaknesses, PHP takes up of the defined majority of the web (22%) based on data from Among the most popular frameworks for web development with PHP is Laravel, and it can be a great choice for making websites with REST APIs. 

Once you build a REST API, you can easily use it to display data from the main server to another website, chatbots, or mobile apps. However, with transferring data to the web comes the concern of security. While transferring data around the web, you may not want that kind of data open and available for anyone to pick off from. One solution for this on any framework is to provide a layer of security for your REST API with a user API key to authenticate an authorized user. To use it, you can create a url which will include a check on an access (or API key) verification before you can see the data. If the access key is not verified, then the user is blocked from seeing or accessing the data. 


This article will assume you already working on a Laravel app and ready to create a REST API with it. If you are not familiar with Laravel, you should stop here and go to the tutorials to build an app with the framework.  

Creating a REST API with Laravel

Before we proceed with working on securing any REST APIs on our Laravel app, I’ll briefly discuss how to make one. For this article, I’ll focus on a GET method in which we retrieve all rows from a database column and display it in a JSON format. As an example, the scenario we’re going to use here will be to retrieve a list of all articles from a blog site. While it may not be that relevant, our Article.php model will have the following fields: an id, image, title, and the article content. Our ArticleController.php file is where we may have other Create, Read, Update, and Delete functions. 

Within our Article Controller and assuming we have use App\Article; called at the top of our file, we’ll add in a simple new function for our API:  

//REST API for all articles

    public function indexAPI()


        $articles = Article::orderBy('created_at', 'desc')->get();

        return $articles;


Once we do that, all we have to add in on our routes to call the API is:

Route::get('/articles/api/', 'ArticleController@indexAPI');

This is the most simple REST API you can build with Laravel, and it can be done within minutes! If you look at the API, you should be able to see the information for your articles listed in JSON. 

Creating the User Access Key

With the basics of creating a REST API out of the way, we can now create a user key for each user. We have to create a new database migration which we will call on the command line: php artisan make:migration create_user_access_key. In it, we’ll add a new field named access_key to the existing user model which can be left blank. Within the migration file, add the following lines:  

Schema::table('user', function (Blueprint $table) {

            $table->longtext('access_key', 15)->nullable();     });

Once completed, you can run php artisan migrate, and the access_key field should be added for each user. Usually the access keys will be a random combination of an alphanumeric value, which can be done grammatically or manually. For example, your own site account can have the access key value of “A2K231” anytime to see the data.  

With this, our goal is to make it so any authorized user with an API key can access the site using a url addition of “/article/api/access_key= [ access key here ].” We’ll create a middleware with the line php artisan make:middleware APIkey. Within your new middleware file, your code should look like this: 


namespace App\Http\Middleware;

use App\User;

use Closure;

class APIkey {

    public function handle($request, Closure $next)


       if ($request->apikey == '') {

            return redirect('/');

        } else { 

            $users = User::where('access_key', $request->apikey)->count();

            if ($users != 1) {

              return response("Invalid access key");

            } else { 

              return $next($request);



   } }

Before we can use the middleware, we’ll register it on the kernel file in Http/Kernel.php within the “protected $routeMiddleware” area. It should now look something like this:  

protected $routeMiddleware = [

        //add our APIkey middleware

        'APIkey' => \App\Http\Middleware\APIkey::class,


Now we can change our route file one last time: 


Route::get('/articles/api/access_key={apikey}, 'ArticleController@indexAPI')->middleware('APIkey');

By now, you will be able to replace the apikey value with A2K231, and see the results in JSON. Otherwise, the middleware will give a response saying “Invalid API key.”

This is just a start to securing API’s, which will involve authorization methods such as creating access tokens or encrypting user information. It should work if you decide to use it between apps on different servers provided you enable CORs in the header. 

Contact Form