Learn to use laravel guard by creating an ads network
Tags: laravel, php, auth, authentication
Published: 2020-08-05 20:19:11

---
title: Learn to use laravel guard by creating an ads network
published: true
description: A quick introduction to multi-auth using laravel guard  
tags: laravel,php,auth,authentication
cover_image: https://res.cloudinary.com/open-source/image/upload/v1596649639/articles/laraauth_bw4kqs.png
---
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;
 <b>Advertiser:</b>As the name sound, the user who come to the website to advertise his/her products and services.<br>
<b>Publisher:</b>The publisher can be a blogger,app owner,web masters who want to monetize his/her contents.<br>


<b> Admin:</b> An Admin in this case is the owner of the network.<br>
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.<br>
   <code>php artisan make:model Advertiser -m</code> to create both model and migration file for advertiser.
repeat same for publishers, admin by running the following code<br>
  <code>php artisan make:model Publisher -m</code>
  <code>php artisan make:model Admin -m</code>
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
<?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',
    ];
}

```

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

<br>
```php

  
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
```

Yey,its time to actually create our guard, go to <code>config/auth.php </code>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.

```php
 'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
       
        'api' => [
            'driver' => 'token',
            'provider' => 'users',
            'hash' => false,
        ],
    ],

```

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.

```php

'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"
```

scroll down while still in the <code>config/app.php</code> 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'
```php
//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,
        ],
```


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.
<code>php artisan make:middleware AdminAuth</code>
<code>php artisan make:middleware AdvertiserAuth</code>
<code>php artisan make:middleware PublisherAuth</code>


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

```php

<?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
    }
}


```

The last step to take now is to register our middlewares in the  app/Http/kernel.php file on the array values of the <code>$routeMiddleware </code> properties.
in the <code>$routeMiddleware </code> 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
```php

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

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


```php


 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
});

```
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 ,<b>its not recommended</b> & overtime,it can also become more harder to maintain.