How To Add National Guard Service To A Resume
You will need PHP 7+, Laravel 5.6+, Composer and Laravel installer. Some knowledge of PHP and Laravel will be helpful.
If you have used Laravel for a while, you should have heard a lot about multiple authentications. Y'all should have besides heard the term "guards" used ofttimes. But if you are fairly new to Laravel, yiou may not notwithstanding understand these concepts.
Multiple authentications arrive possible for you to directly different classes of users to differing parts of the aforementioned awarding.
There are many reasons why y'all may want to use multiple authentications in your Laravel application. For instance:
- If you lot have a large application that runs an enterprise with many departments.
- If customers and employees interact with the production and services of the visitor through the same application.
- If the awarding also has a blog and there is a department in the company responsible for handling the blog.
Let's assume all of the above examples are relevant. In this awarding there are three sets of users:
- Customers: these users will need a specific hallmark procedure to access the arrangement.
- Weblog writers: these users will likely need a totally different authentication process and may even accept roles to enable a more robust content direction process.
- The rest of the company: these roles can exist split up to represent different functions with different duties and administrative allowances.
Now, let us look at how to create multiple authentications for our different classes of users.
Prerequisites
- Knowledge of PHP (version >= 7.i.three).
- Cognition of Laravel (version 5.6.x).
- Composer is installed on your figurer (version >= ane.3.two).
- Laravel installer is installed on your computer.
Getting started
If you lot checked off all the items on the prerequisites list, then this tutorial is already looking solid for you. We will create a Laravel app that has 3 user classes — admin, writer, user. We will make guards for the 3 user classes and restrict different parts of our application based on those guards.
Create the application
We need to create a new Laravel application. Run the post-obit command on your final to create a new Laravel application:
$ laravel new multi -auth $ cd multi-auth
Create the database
We will use SQLite database for our application. It is lightweight, fast and uses a simple flat file. Create a database file with the post-obit command:
$ bear upon database/database.sqlite
Open the .env
file in your application directory and modify the following section:
DB_CONNECTION =mysql DB_HOST = 127.0 .0 .1 DB_PORT = 3306 DB_DATABASE =homestead DB_USERNAME =homestead DB_PASSWORD =secret
To:
DB_CONNECTION = /absolute/path/to/database.sqlite
This volition ensure our application uses the SQLite driver for database connections.
Creating migrations
We will make migrations for the admins and writers tables as Laravel comes with a users migration. They will be equally simple as the users table, but you lot can extend them further based on your specific needs.
Create migration for admins
To make the admins table, run the following command:
$ php artisan make:migration create_admins_table
From the database/migrations
directory, open the admins migrations file and edit it as follows:
// database/migrations/<timestamp>_create_admins_table.php [ ... ] public function up ( ) { Schema :: create ( 'admins' , office ( Design $table ) { $table -> increments ( 'id' ) ; $table -> string ( 'proper name' ) ; $tabular array -> string ( 'electronic mail' ) -> unique ( ) ; $table -> string ( 'countersign' ) ; $table -> boolean ( 'is_super' ) -> default ( false ) ; $table -> rememberToken ( ) ; $table -> timestamps ( ) ; } ) ; } [ ... ]
Nosotros have created a simple migration and divers the columns nosotros desire the admin table to have. Eloquent provides methods that represent datatypes of our database tabular array. We utilize them to define the datatypes of our table columns.
Remember, you can e'er configure your tabular array how you please.
Create migration for writers
To make the writers table, run the post-obit command:
$ php artisan make:migration create_writers_table
Now, open the writers migrations file and edit information technology as follows:
database/migrations/ <timestamp>_create_writers_table.php [ ... ] public part upwards ( ) { Schema :: create ( 'writers' , part ( Blueprint $table ) { $table -> increments ( 'id' ) ; $tabular array -> string ( 'name' ) ; $table -> string ( 'email' ) -> unique ( ) ; $tabular array -> cord ( 'password' ) ; $table -> boolean ( 'is_editor' ) -> default ( false ) ; $tabular array -> rememberToken ( ) ; $tabular array -> timestamps ( ) ; } ) ; } [ ... ]
We just created a simple migration and defined the columns we want the writers table to have. Eloquent provides methods that represent datatypes of our database table, then it is piece of cake to decide what we want each one to be.
Migrate the database
At present that nosotros have defined our tables, let us migrate the database:
$ php artisan migrate
Set up the models
We have different classes of users for our application, and they utilize different database tables. To use these unlike tables for authentication, we have to ascertain models for them. These models will be like the user model and extends the Authenticable grade.
Admin model
To make the model for the admins, run the following command:
$ php artisan make:model Admin
Open up the Admin model in app/Admin.php
and add the following:
// app/Admin.php <?php namespace App ; employ Illuminate\Notifications\Notifiable ; utilize Illuminate\Foundation\Auth\User as Authenticatable; course Admin extends Authenticatable { use Notifiable ; protected $guard = 'admin' ; protected $fillable = [ 'name' , 'e-mail' , 'password' , ] ; protected $subconscious = [ 'countersign' , 'remember_token' , ] ; }
When you intend to apply a model for authentication, and you lot programme to not use the default user guard, it is important you specify the baby-sit it will use. In our example, it will use the admin guard.
We also defined some of our database columns every bit fillable by putting them in the fillable assortment. This tells Laravel the following well-nigh the model:
When I call your create or update method and I pass you an array, take only these items (read: items in the fillable array).
This way, we will forestall a scenario where a user can featherbed any of our checks and insert or update a record we do non wish for them to update.
For the hidden
array, nosotros tell Laravel not to return those columns when we return the model to either our API or view.
Writers model
To brand the model for the writers, run the following control:
$ php artisan make:model Writer
Then open the Author
model and replace with the following:
// app/Author.php <?php namespace App ; use Illuminate\Notifications\Notifiable ; apply Illuminate\Foundation\Auth\User every bit Authenticatable; class Writer extends Authenticatable { employ Notifiable ; protected $guard = 'writer' ; protected $fillable = [ 'name' , 'e-mail' , 'password' , ] ; protected $hidden = [ 'password' , 'remember_token' , ] ; }
Define the guards
Laravel guards ascertain how users are authenticated for each request. Laravel comes with some guards for authentication, but nosotros can as well create ours too. This will enable us to use Laravel's default hallmark system with our Admin
and Writer
models too.
Open config/auth.php
and add the new guards edit equally follows:
// config/auth.php <?php [ ... ] 'guards' => [ [ ... ] 'admin' => [ 'commuter' => 'session' , 'provider' => 'admins' , ] , 'writer' => [ 'driver' => 'session' , 'provider' => 'writers' , ] , ] , [ ... ]
We added two new guards admin
and writer
and set their providers. These providers tell Laravel what to utilize for authentication or validation when nosotros try to use the guard.
Now, add the post-obit to the providers array:
// config/auth.php [ ... ] 'providers' => [ [ ... ] 'admins' => [ 'driver' => 'eloquent' , 'model' => App\Admin :: class , ] , 'writers' => [ 'commuter' => 'eloquent' , 'model' => App\Writer :: course , ] , ] , [ ... ]
Now, nosotros have set the providers we defined along with the guards above. We set the driver to be eloquent
since nosotros are using Eloquent ORM as our database manager.
Let'due south say nosotros wish to use another ORM similar RedBeanPHP for managing our database, nosotros tin can then gear up the driver to say redbeanphp
instead of eloquent
. For the model, nosotros pass the model nosotros want that provider to use.
Gear up up the controllers
To apply our guards for authentication, we tin can either modify the existing hallmark controllers or create new ones. You can cull which to apply based on your specific needs. In this tutorial, we will modify these controllers.
Modify LoginController
Open the LoginController
in app/Http/Controllers/Auth
and edit every bit follows:
// app/Http/Controllers/Auth/LoginController.php <?php namespace App\Http\Controllers\Auth ; use App\Http\Controllers\Controller ; use Illuminate\Foundation\Auth\AuthenticatesUsers ; [ ... ] use Illuminate\Http\Asking ; use Auth ; [ ... ] class LoginController extends Controller { [ ... ] public role __construct ( ) { $this -> middleware ( 'guest' ) -> except ( 'logout' ) ; $this -> middleware ( 'guest:admin' ) -> except ( 'logout' ) ; $this -> middleware ( 'guest:writer' ) -> except ( 'logout' ) ; } [ ... ] }
We set the middleware to restrict access to this controller or its methods. It is important nosotros divers all the different types of guests in the controller. This fashion, if one blazon of user is logged in and you try to use another user blazon to log in, it volition redirect you to a predefined hallmark folio.
Run across it this fashion: If I log in on my computer every bit an administrator, and my colleague who is a writer also tries to log into his business relationship every bit a writer, he will not be able to.
This bank check is important, then we practise non mess upward session information and potentially decadent our awarding data.
Now, define the login for admins:
// app/Http/Controllers/Auth/LoginController.php [ ... ] public function showAdminLoginForm ( ) { return view ( 'auth.login' , [ 'url' => 'admin' ] ) ; } public function adminLogin ( Request $asking ) { $this -> validate ( $asking , [ 'electronic mail' => 'required|e-mail' , 'countersign' => 'required|min:6' ] ) ; if ( Auth :: guard ( 'admin' ) -> attempt ( [ 'email' => $request -> e-mail , 'countersign' => $request -> password ] , $request -> get ( 'recall' ) ) ) { render redirect ( ) -> intended ( '/admin' ) ; } return back ( ) -> withInput ( $request -> only ( 'electronic mail' , 'recollect' ) ) ; } [ ... ]
Nosotros have set upwards a method to render the login page for an admin. We volition use the aforementioned page for all the user types and only change the URL they get sent to. Saves u.s.a. a lot of code we could avert writing.
Nosotros too divers the adminLogin
method which checks that the right credentials are supplied. Then we attempt to log a user in with the admin
guard. It is important nosotros fix this guard when attempting a login and so that the Auth facade will cheque the right tabular array matching credentials. It volition also prepare upward our authentication so we tin restrict pages based on the blazon of user who is logged in.
Nosotros redirect an authenticated user to a specific URL and send an unauthenticated user back to the login page.
Now, let us do the same thing simply for the writers:
// app/Http/Controllers/Auth/LoginController.php [ ... ] public function showWriterLoginForm ( ) { return view ( 'auth.login' , [ 'url' => 'writer' ] ) ; } public function writerLogin ( Request $request ) { $this -> validate ( $request , [ 'e-mail' => 'required|email' , 'countersign' => 'required|min:half-dozen' ] ) ; if ( Auth :: baby-sit ( 'writer' ) -> attempt ( [ 'email' => $asking -> email , 'password' => $request -> password ] , $request -> become ( 'remember' ) ) ) { return redirect ( ) -> intended ( '/author' ) ; } return back ( ) -> withInput ( $asking -> only ( 'email' , 'remember' ) ) ; } [ ... ]
And our login is set. Hurray!!!
Modify RegisterController
Open the RegisterController
and edit as follows:
// app/Http/Controllers/Auth/RegisterController.php <?php [ ... ] namespace App\Http\Controllers\Auth ; utilize App\User ; use App\Admin ; utilize App\Writer ; utilize App\Http\Controllers\Controller ; use Illuminate\Support\Facades\Hash ; apply Illuminate\Support\Facades\Validator ; use Illuminate\Foundation\Auth\RegistersUsers ; utilise Illuminate\Http\Asking ; [ ... ] class RegisterController extends Controller { [ ... ] public function __construct ( ) { $this -> middleware ( 'guest' ) ; $this -> middleware ( 'guest:admin' ) ; $this -> middleware ( 'guest:writer' ) ; } [ ... ] }
We have prepare the middleware the controller volition use, just similar we did with the LoginController
.
Now, allow usa set upward the methods to return the registration pages for the different users:
// app/Http/Controllers/Auth/RegisterController.php [ ... ] public role showAdminRegisterForm ( ) { return view ( 'auth.register' , [ 'url' => 'admin' ] ) ; } public role showWriterRegisterForm ( ) { render view ( 'auth.annals' , [ 'url' => 'writer' ] ) ; } [ ... ]
This is like to what we did for showing dissimilar login pages.
Now, we can define our methods for creating an admin:
// app/Http/Controllers/Auth/RegisterController.php [ ... ] protected function createAdmin ( Request $asking ) { $this -> validator ( $request -> all ( ) ) -> validate ( ) ; $admin = Admin :: create ( [ 'proper name' => $request [ 'proper noun' ] , 'email' => $request [ 'email' ] , 'countersign' => Hash :: make ( $request [ 'password' ] ) , ] ) ; return redirect ( ) -> intended ( 'login/admin' ) ; } [ ... ]
Next, let united states of america define methods for creating a writer:
// app/Http/Controllers/Auth/RegisterController.php [ ... ] protected function createWriter ( Request $request ) { $this -> validator ( $request -> all ( ) ) -> validate ( ) ; $author = Author :: create ( [ 'proper name' => $request [ 'proper name' ] , 'email' => $request [ 'electronic mail' ] , 'countersign' => Hash :: make ( $request [ 'password' ] ) , ] ) ; render redirect ( ) -> intended ( 'login/writer' ) ; } [ ... ]
And registration is complete.
Set up authentication pages
We will use Laravel'due south auth scaffolding to generate pages and controllers for our hallmark system. Run the following command to generate the hallmark pages:
$ php artisan make:auth
This will generate view files in resources/views/auth
along with routes to handle basic authentication for our application. Is that absurd or what?
Open the login.blade.php
file and edit as follows:
// resources/views/auth/login.blade.php [ ... ] <div class = "container" > <div class = "row justify-content-center" > <div class = "col-md-8" > <div form = "card" > <div class = "carte-header" > { { isset ( $url ) ? ucwords ( $url ) : "" } } { { __ ( 'Login' ) } } < /div> <div class = "card-body" > @isset ( $url ) <form method= "POST" activity= '{{ url("login/$url") }}' aria-characterization= "{{ __('Login') }}" > @else <class method= "POST" action= "{{ route('login') }}" aria-label= "{{ __('Login') }}" > @endisset @csrf [ ... ] < /div>
Nosotros are checking if nosotros passed a url
parameter to the page when nosotros called it. If we did, we change the forms action to utilise the url
parameter. We also modified the header of the form so that it shows the blazon of user based on their login parameter.
Open the register.blade.php
file and edit as follows:
// resources/views/auth/register.blade.php [ ... ] <div class = "container" > <div form = "row justify-content-middle" > <div grade = "col-medico-8" > <div course = "carte du jour" > <div class = "card-header" > { { isset ( $url ) ? ucwords ( $url ) : "" } } { { __ ( 'Register' ) } } < /div> <div class = "carte-torso" > @isset ( $url ) <form method= "POST" action= '{{ url("register/$url") }}' aria-label= "{{ __('Register') }}" > @else <form method= "POST" action= "{{ route('register') }}" aria-label= "{{ __('Register') }}" > @endisset @csrf [ ... ] < /div>
Nosotros replicated what nosotros did for login page here.
Create the pages authenticated users will access
Now that nosotros are done setting up the login and register page, let united states of america make the pages the admin and writers will see when they are authenticated. Open up the terminal and run the post-obit commands to create new files. Adjacent, we will insert the corresponding code snippets to the files.
$ touch resources/views/layouts/auth.bract.php $ bear on resources/views/admin.blade.php $ touch resources/views/writer.bract.php $ bear on resource/views/domicile.bract.php
Insert this code block into the auth.blade.php
file:
// resources/views/layouts/auth.blade.php < ! DOCTYPE html> <html lang= "{{ str_replace('_', '-', app()->getLocale()) }}" > <caput> <meta charset= "utf-8" > <meta http-equiv= "10-UA-Compatible" content= "IE=edge" > <meta name= "viewport" content= "width=device-width, initial-scale=1" > < ! -- CSRF Token -- > <meta proper noun= "csrf-token" content= "{{ csrf_token() }}" > <title> { { config ( 'app.name' , 'Laravel' ) } } < /title> < ! -- Scripts -- > <script src= "{{ nugget('js/app.js') }}" defer> < /script> < ! -- Fonts -- > <link rel= "dns-prefetch" href= "https://fonts.gstatic.com" > <link href= "https://fonts.googleapis.com/css?family=Raleway:300,400,600" rel= "stylesheet" type= "text/css" > < ! -- Styles -- > <link href= "{{ asset('css/app.css') }}" rel= "stylesheet" > < /caput> <torso> <div id= "app" > <nav class = "navbar navbar-expand-md navbar-light navbar-laravel" > <div class = "container" > <a grade = "navbar-brand" href= "{{ url('/') }}" > { { config ( 'app.name' , 'Laravel' ) } } < /a> <button class = "navbar-toggler" type= "button" data-toggle= "plummet" information-target= "#navbarSupportedContent" aria-controls= "navbarSupportedContent" aria-expanded= "false" aria-characterization= "{{ __('Toggle navigation') }}" > <span class = "navbar-toggler-icon" > < /bridge> < /push button> <div grade = "plummet navbar-plummet" id= "navbarSupportedContent" > < ! -- Left Side Of Navbar -- > <ul class = "navbar-nav mr-auto" > < /ul> < ! -- Correct Side Of Navbar -- > <ul class = "navbar-nav ml-auto" > < ! -- Authentication Links -- > <li grade = "nav-item dropdown" > <a id= "navbarDropdown" class = "nav-link dropdown-toggle" href= "#" role= "button" information-toggle= "dropdown" aria-haspopup= "true" aria-expanded= "false" v-pre> Hullo There <span class = "caret" > < /span> < /a> <div grade = "dropdown-bill of fare dropdown-carte-right" aria-labelledby= "navbarDropdown" > <a class = "dropdown-detail" href= "{{ route('logout') }}" onclick= "event.preventDefault(); document.getElementById('logout-class').submit();" > { { __ ( 'Logout' ) } } < /a> <form id= "logout-form" action= "{{ route('logout') }}" method= "Mail" style= "display: none;" > @csrf < /form> < /div> < /li> < /ul> < /div> < /div> < /nav> <main class = "py-4" > @yield ( 'content' ) < /chief> < /div> < /body> < /html>
Side by side, insert this code block into the admin.blade.php
file:
// resource/views/admin.blade.php @extends ( 'layouts.auth' ) @section ( 'content' ) <div class = "container" > <div class = "row justify-content-center" > <div class = "col-doctor-8" > <div grade = "bill of fare" > <div class = "card-header" >Dashboard< /div> <div class = "menu-body" > Hi boss! < /div> < /div> < /div> < /div> < /div> @endsection
Open the writer.blade.php
file and edit as follows:
// resources/views/writer.blade.php @extends ( 'layouts.auth' ) @section ( 'content' ) <div course = "container" > <div class = "row justify-content-middle" > <div grade = "col-physician-8" > <div class = "card" > <div class = "card-header" >Dashboard< /div> <div course = "card-trunk" > How-do-you-do in that location, awesome writer < /div> < /div> < /div> < /div> < /div> @endsection
Finally, open the home.blade.php
file and replace with the following:
// resource/views/abode.blade.php @extends ( 'layouts.auth' ) @section ( 'content' ) <div course = "container" > <div class = "row justify-content-centre" > <div class = "col-md-8" > <div form = "card" > <div grade = "card-header" >Dashboard< /div> <div form = "carte-body" > Hi there, regular user < /div> < /div> < /div> < /div> < /div> @endsection
Fix the routes
Our application is well-nigh ready. Let us define the routes to access all the pages we have created and so far. Open up the routes/web.php
file and supervene upon with the following:
// routes/web.php <?php Road :: view ( '/' , 'welcome' ) ; Auth :: routes ( ) ; Route :: get ( '/login/admin' , 'Auth\LoginController@showAdminLoginForm' ) ; Route :: get ( '/login/author' , 'Auth\LoginController@showWriterLoginForm' ) ; Road :: become ( '/annals/admin' , 'Auth\RegisterController@showAdminRegisterForm' ) ; Route :: go ( '/register/writer' , 'Auth\RegisterController@showWriterRegisterForm' ) ; Road :: post ( '/login/admin' , 'Auth\LoginController@adminLogin' ) ; Route :: post ( '/login/author' , 'Auth\LoginController@writerLogin' ) ; Road :: post ( '/annals/admin' , 'Auth\RegisterController@createAdmin' ) ; Route :: post ( '/register/writer' , 'Auth\RegisterController@createWriter' ) ; Route :: view ( '/domicile' , 'dwelling house' ) -> middleware ( 'auth' ) ; Route :: view ( '/admin' , 'admin' ) ; Route :: view ( '/writer' , 'writer' ) ;
Modify how our users are redirected if authenticated
It is important you modify how users are redirected when they are authenticated. Laravel past default redirects all authenticated users to /domicile
. We will become the error below if nosotros practise not modify the redirection.
Then, to solve that, open the app/Http/Controllers/Middleware/RedirectIfAuthenticated.php
file and replace with this:
// app/Http/Controllers/Middleware/RedirectIfAuthenticated.php <?php namespace App\Http\Middleware ; utilize Closure ; use Illuminate\Support\Facades\Auth ; class RedirectIfAuthenticated { public office handle ( $asking , Closure $next , $guard = null ) { if ( $baby-sit == "admin" && Auth :: guard ( $guard ) -> check ( ) ) { return redirect ( '/admin' ) ; } if ( $guard == "writer" && Auth :: guard ( $guard ) -> cheque ( ) ) { return redirect ( '/writer' ) ; } if ( Auth :: guard ( $guard ) -> bank check ( ) ) { return redirect ( '/dwelling house' ) ; } return $next ( $asking ) ; } }
The RedirectIfAuthenticated
middleware receives the auth baby-sit as a parameter. This middleware is triggered when nosotros try to visit whatever folio meant for authenticated users. We can then determine the type of authentication the user has and redirect them appropriately.
Modify hallmark exception handler
There is a little abrasive thing that would happen when a user is redirected. Y'all would expect that if a user tries to access say /author
but is not authenticated, that the user is redirected to /login/writer
, yes? Well, they don't. They get redirected to /login
which is not what nosotros desire.
To ensure that when a user tries to visit /author
they are redirected to /login/writer
or the same for /admin
, we have to alter the exception handler. Open the handler file in app/Exceptions
and add the following:
// app/Exceptions/Handler.php <?php namespace App\Exceptions ; utilize Exception ; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; [ ... ] use Illuminate\Auth\AuthenticationException ; use Auth ; [ ... ] class Handler extends ExceptionHandler { [ ... ] protected function unauthenticated ( $request , AuthenticationException $exception ) { if ( $request -> expectsJson ( ) ) { return response ( ) -> json ( [ 'mistake' => 'Unauthenticated.' ] , 401 ) ; } if ( $request -> is ( 'admin' ) || $request -> is ( 'admin/*' ) ) { return redirect ( ) -> invitee ( '/login/admin' ) ; } if ( $request -> is ( 'writer' ) || $request -> is ( 'writer/*' ) ) { render redirect ( ) -> invitee ( '/login/writer' ) ; } render redirect ( ) -> guest ( route ( 'login' ) ) ; } }
The unauthenticated
method we just added resolves this issue we accept. It receives an AuthenticationExpection
exception by default which carries that baby-sit information. Sadly, we cannot access that, because it is protected (hopefully, Laravel v.7 will come with a mode to access it).
Our workaround is to use request→is()
. This checks the URL we are trying to access. It can besides check the URL pattern if we do not take an absolute URL or if nosotros take a road grouping.
In our instance, we first cheque if we received a JSON asking and handle the exception separately. And then we check if nosotros are trying to admission /admin
or any URL preceded by admin
. We redirect the user to the appropriate login page. We as well do the check for writer
as well.
This is a good workaround for us, but it means we must know the absolute URL we want to access, or at to the lowest degree accept the same prefix for all routes that will be protected by our baby-sit.
Run the application
Now that our application is prepare, run the post-obit command to go it upwards:
$ php artisan serve
It should typically be available on http://localhost:8000
.
Remember to visit
http://localhost:8000/annals/writer
andhttp://localhost:8000/register/admin
to annals writers and admins respectively. Then visithttp://localhost:8000/login/writer
andhttp://localhost:8000/login/admin
to login the writers and admins respectively.
Conclusion
In this tutorial, we dived deep into Laravel authentication. We defined multiple guards to handle multiple authentications and access control. We too handle redirection for authenticated user and redirection for an unauthenticated user.
If you followed this guide thoroughly, you lot will exist able to prepare up the base of operations authentication for an awarding with different user classes (possibly a multitenant awarding). Be that as information technology may, try extending what y'all accept seen and share what you come with.
The source code to the application in this article is available on GitHub.
Source: https://pusher.com/tutorials/multiple-authentication-guards-laravel/
Posted by: matthewsmande1942.blogspot.com
0 Response to "How To Add National Guard Service To A Resume"
Post a Comment