Chat with us, powered by LiveChat

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.

Setup Laravel 5.7 Application in Just 1-click on Different Cloud Providers Like GCE , AWS , DO , Linode , Vultr Deploy Now!

How to Setup Laravel Login Authentication in Simple and Easy Steps

Updated on September 1, 2016

4 Min Read
Reading Time: 4 minutes

In this tutorial, I will discuss how to implement Laravel login authentication. An important feature of this Laravel 5.5 authentication example implementation is that it filters out and generates an error whenever the authentication credentials (for example, email and/or password) are incorrectly entered by the user(s).

Laravel-Login-Authentication-Banner

Prerequisites for Laravel 5.5 custom authentication:

  1. Cloudways Server. Get your server on Cloudways if you do not have one.
  2. Launch a Laravel 5.5 app.

Step 1: Setup the Database

  • Go to your Laravel application on the Cloudways server.
  • Click on Launch Database.
  • Click on Create Table. Name the new table users and select innoDB and ascii_general
  • Add the following columns in the table:
    • id (int)   (Check AutoIncrement A.I.)
    • name (text)
    • username (text)
    • email (text)
    • password (text)
    • remember_token (text)
    • timestamp (time)
  • Click Save
  • Now Click New Item and then add the following user:
    • Name: Harry Potter
    • Username: BoyWhoLived
    • Email: harrypotter@hogwarts.edu.uk
    • Password: caputdraconis
  • Click Save

Tailor Made Cloud Hosting For Different PHP Frameworks

From Laravel to CodeIgniter, We Have Got You Covered On All PHP Frameworks!

Step 2: Setup the Routes

$ vim app/Http/routes.php

Here lies all the endpoints.

Let’s make three endpoints:

  1. Post Call to submit the form
  2. Get Call to show the login form
  3. To LogOut.
<?php
/*

|--------------------------------------------------------------------------

| Application Routes

|--------------------------------------------------------------------------

*/

// route to show the login form

Route::get('login', array(
	'uses' => 'MainController@showLogin'
));

// route to process the form

Route::post('login', array(
	'uses' => 'MainController@doLogin'
));
Route::get('logout', array(
	'uses' => 'MainController@doLogout'
));
Route::get('/',
function ()
	{
	return view('welcome');
	});

Step 3: Make the Controllers

$ vim app/Http/Controllers/MainController.php

I will extend MainController from the Base Controller and make three functions to show login, check the login and for logging out.

Following is the code for MainController:

<?php
namespaceAppHttpControllers;
useRedirect;
useAuth;
useInput;
useIlluminateSupportFacadesValidator;
useIlluminateFoundationBusDispatchesJobs;
useIlluminateRoutingController as BaseController;
useIlluminateFoundationValidationValidatesRequests;
useIlluminateFoundationAuthAccessAuthorizesRequests;
useIlluminateFoundationAuthAccessAuthorizesResources;
useIlluminateHtmlHtmlServiceProvider;
class MainController extends BaseController

	{
	public

	function showLogin()
		{

		// Form View

		return view('login');
		}

	public

	function doLogout()
		{
		Auth::logout(); // logging out user
		return Redirect::to('login'); // redirection to login screen
		}

	public

	function doLogin()
		{

		// Creating Rules for Email and Password

		$rules = array(
			'email' => 'required|email', // make sure the email is an actual email
			'password' => 'required|alphaNum|min:8'

			// password has to be greater than 3 characters and can only be alphanumeric and);
			// checking all field

			$validator = Validator::make(Input::all() , $rules);

			// if the validator fails, redirect back to the form

			if ($validator->fails())
				{
				return Redirect::to('login')->withErrors($validator) // send back all errors to the login form
				->withInput(Input::except('password')); // send back the input (not the password) so that we can repopulate the form
				}
			  else
				{

				// create our user data for the authentication

				$userdata = array(
					'email' => Input::get('email') ,
					'password' => Input::get('password')
				);

				// attempt to do the login

				if (Auth::attempt($userdata))
					{

					// validation successful
					// do whatever you want on success

					}
				  else
					{

					// validation not successful, send back to form

					return Redirect::to('checklogin');
					}
				}
			}
		}

Step 4: Setup the View

Now let’s make the view, which will contain the HTML code of the app.

$ vim resources/views/checklogin.blade.php

The .blade.php extension lets Laravel know that I am using its Blade Templating system.

 

Here is the HTML code for this file.

<!doctype html>
<html>
   <head>
      <title>My Login Page</title>
   </head>
   <body>
      <
      {{ Form::open(array('url' => 'login')) }}
      <h1>Login</h1>
      <!-- if there are login errors, show them here -->
      <p>
         {{ $errors->first('email') }}
         {{ $errors->first('password') }}
      </p>
      <p>
         {{ Form::label('email', 'Email Address') }}
         {{ Form::text('email', Input::old('email'), array('placeholder' => 'check@CZX.com')) }}
      </p>
      <p>
         {{ Form::label('password', 'Password') }}
         {{ Form::password('password') }}
      </p>
      <p>{{ Form::submit('Submit!') }}</p>
      {{ Form::close() }}

Now let’s check how the app looks!

Laravel Login

This is a simple example of how you could implement login authentication in a Laravel app.

Another Laravel 5.5 login and registration Setup

Here is a GIF that explains the entire process:

Database Migration

In a Laravel powered app, database configuration is handled by two files: env and config/database.php. In my case, I created a database with the name loginuser. The Cloudways Database Manager makes the entire process very easy.

Next, run the following command in the terminal to create tables in the database:

Login to SSH terminal by using Master Credentials and go to the application folder by using the command

$ ls
applications
$ cd applications
applications$ ls
pjbeasusxr trxbnbphae
applications$ cd trxbnbphae/
trxbnbphae$ cd public_html/

 

php artisan migrate

Now, when you check the database, you will see that the tables have been created successfully.

Laravel 5.5 authentication

php artisan make:auth

This command should be used in fresh applications and will install a layout view, registration and login views, as well as routes for all authentication endpoints.

Register

Login

Use Username for Authentication

Laravel uses the provided email address as the default authentication field. However, users prefer to use their username instead of emails. To change the default behavior, here is how to define a username in the

Login Controller

public function username()
{ return 'username';}

If you have a question about this Laravel 5.5 authorization example or wish to add to the conversation about Laravel 5.5 login example, please leave a comment below.

 

Share your opinion in the comment section. COMMENT NOW

Noor Ali

Noor Ali is an Associate Software Engineer at Cloudways. He loves to solve technical problems through programming and mathematics.

Launch Laravel apps with 1-Click Install. Painless Server Management

Deploy your apps on optimized Laravel hosting servers.

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

THERE’S MORE TO READ.