DEV Community

Cover image for Learn to use laravel guard by creating an ads network
Olaniyi Philip Ojeyinka
Olaniyi Philip Ojeyinka

Posted on • Updated on

Learn to use laravel guard by creating an ads network

In this article,we will be discussing how to use laravel authentication guard by creating a guard for an advertising network web app,think of Adsense,Bidvertiser etc.
Before we start discussing the laravel guard, you may be wondering when do i need laravel guard ? well, you need laravel guard when working on an app that serve different type of users or even if you want to create an admin dashboard for that your web app that authenticate user .

Typical advertising network website have more than three different type of users but in our case ,we are going to be creating just three types of users which are;
Advertiser:As the name sound, the user who come to the website to advertise his/her products and services.

Publisher:The publisher can be a blogger,app owner,web masters who want to monetize his/her contents.

Admin: An Admin in this case is the owner of the network.

I'm assuming you already have your laravel project ready.
The first step we are to take is to create a model and migrations for advertisers,publishers,and the admin.

php artisan make:model Advertiser -m to create both model and migration file for advertiser.
repeat same for publishers, admin by running the following code

php artisan make:model Publisher -m
php artisan make:model Admin -m
The next step is to extend the authenticatable class for us to be able to use some of the already built authentication features.

So your Advertiser,Admin , Publisher model contents should look as the following code sample

<?php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
//change the class name to publisher for publisher model
//and Admin for the admin model
class Advertiser extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

Enter fullscreen mode Exit fullscreen mode

We are getting there 🙄,next step is to add the following columns to the advertiser,publisher and admin migrations we created earlier.



            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
Enter fullscreen mode Exit fullscreen mode

Yey,its time to actually create our guard, go to config/auth.php file,you can see the whole file returns a multi-array.lookout for the array element with key as "guards" as in the code below.

 'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'token',
            'provider' => 'users',
            'hash' => false,
        ],
    ],

Enter fullscreen mode Exit fullscreen mode

The sub element with key "web" is the guard for the default user that comes with laravel.
now we are to add code like that to the array for each of our own user types.See the code below.


'advertiser' => [
            'driver' => 'session',
            'provider' => 'advertisers',
        ],
'publisher' => [
            'driver' => 'session',
            'provider' => 'publishers',
        ],
'admin' => [
            'driver' => 'session',
            'provider' => 'admins',
        ],


//these codes goes in to the values of guards (same level as the "web"
Enter fullscreen mode Exit fullscreen mode

scroll down while still in the config/app.php file ,you will see another key "providers".
The next step is to link our models to the providers as follows by adding the below code to the values of the key 'providers'

//the keys(advertisers,publishers,admins) here are the values we gave to the provider in "guards" array above. 
 'advertisers' => [
            'driver' => 'eloquent',
            'model' => App\Advertiser::class,
        ],
'publishers' => [
            'driver' => 'eloquent',
            'model' => App\Publisher::class,
        ],
'admins' => [
            'driver' => 'eloquent',
            'model' => App\Admin::class,
        ],
Enter fullscreen mode Exit fullscreen mode

Next step is to create a middleware for each of our guards to protect each user types resources.
Run the following commands below to create middlewares for each of our guards.
php artisan make:middleware AdminAuth
php artisan make:middleware AdvertiserAuth
php artisan make:middleware PublisherAuth

Now go into your app/Http/middleware directory,and edit each middlewares we created above as follows:


<?php

namespace App\Http\Middleware;
use Auth;
use Illuminate\Support\Facades\Session;
use Closure;
/*AdvertiserAuth,PublisherAuth in AdvertiserAuth.php ,PublisherAuth.php respectively */
class AdminAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
//change the guard static method parameter to advertiser,publisher 
//incase of  AdvertiserAuth.php ,PublisherAuth.php
/*
note:the parameter value here are the guard we registered in the guard array in config/auth.php file
*/
        if(Auth::guard('admin')->check()){
           return $next($request);

         }
         return redirect()->route('admin.login')->withErrors([ 'Not allowed']);

//redirect here to your corresponding login page
    }
}


Enter fullscreen mode Exit fullscreen mode

The last step to take now is to register our middlewares in the app/Http/kernel.php file on the array values of the $routeMiddleware properties.
in the $routeMiddleware array, the key is the name we can use to call our middlewares in our route.
you are to add our middlewares to the array as follows


protected $routeMiddleware = [...
"advertiser.auth" =>\App\Http\Middleware\AdvertiserAuth::class,
"publisher.auth" =>\App\Http\Middleware\PublisherAuth::class,
"admin.auth" =>\App\Http\Middleware\AdminAuth::class,

]
Enter fullscreen mode Exit fullscreen mode

Now,we can use our guard and middlewares to protect our routes as in the example below.



 Route::middleware(['advertiser.auth'])->group(
        function(){
//protected advertiser routes here
});

 Route::middleware(['publisher.auth'])->group(
        function(){
//protected publisher routes here
});

 Route::middleware(['admin.auth'])->group(
        function(){
//protected admin routes here
});

Enter fullscreen mode Exit fullscreen mode

at last😹,we are done ,while its possible to achieve same result as above by just creating a column of user_type with possible values like advertiser,admin,publisher in the users table ,its not recommended & overtime,it can also become more harder to maintain.

Top comments (0)