Skip to content

Mukesh Chapagain Blog

  • PHP
    • PHP
    • Laravel
    • WordPress
    • Joomla
  • Magento
    • Magento 2
    • Magento Extension
  • Node.js
    • Node.js
    • Javascript
    • jQuery
  • Database
    • MySQL
    • MongoDB
  • Data Science
    • Machine Learning
    • Recommender System
    • Natural Language Processing (NLP)
    • Sentiment Analysis
    • Python
    • R
  • Categories
    • Blockchain
      • Hyperledger Composer
      • Hyperledger-Fabric
    • Other
      • Cryptography
      • Data Structures & Algorithms
      • Git
      • LaTeX
      • Linux
      • Ubuntu
      • Xubuntu
      • Google
      • Google AppScript
  • About
    • About
    • Contact
    • Privacy Policy

Home » Laravel » Laravel: Login Register [Beginner Tutorial]

Laravel: Login Register [Beginner Tutorial]

October 6, 2022November 21, 2016 by Mukesh Chapagain
Categories Laravel Tags authentication, laravel, login, PHP, register
FacebookTweetLinkedInPinPrintEmailShares

This beginner tutorial/article shows how you can create a simple/basic user login and registration application using Laravel. In previous Laravel article, I have described in detail about Creating simple CRUD application in Laravel. In the CRUD article, I have described about Laravel folder structure and artisan command line tool. Hence, in this article, we will directly move towards creating database and tables.

Table of Contents

Toggle
  • Create Database
  • Database Configuration Settings
  • Creating Table
  • Creating Model
  • Routing
  • Creating Controller
  • Views

Create Database

Let’s suppose, that our database name is laravel.

Here’s the MySQL query to create database:


CREATE DATABASE laravel;

Database Configuration Settings

After you create your database, you need to enter your database name and database login credentials in Laravel’s configuration settings file. Laravel’s database configuration file is present at /path-to-laravel-root/config/database.php.

We will be using MySQL database. So, we will edit “mysql” settings (database name, database username, database password, etc.) in database.php file.

Here is the update done by my side. You have to update it according to your database settings.


'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'laravel'), // YOUR DATABASE NAME
            'username' => env('DB_USERNAME', 'root'), // YOUR DATABASE USERNAME
            'password' => env('DB_PASSWORD', 'root'), // YOUR DATABASE PASSWORD
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'strict' => false,
            'engine' => null,
        ],

To use database commands from Artisan Command Line Tool, you also need to update database settings in /path-to-laravel-root/.env file because Artisan fetches database settings from .env file. Here’s the updated .env file on my computer:


DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=root

Creating Table

We will be using Laravel’s Migrations feature to create database table. Migrations files are present in folder your-laravel-root/database/migrations/. From Laravel 5.0.0 onwards, there is a default migration file to create users table. It’s named 2014_10_12_000000_create_user_table.php.

If it’s not present, then you can run the following artisan commands to create one:


php artisan migrate:install
php artisan make:migration create_users_table

This will create a new migration file in your-laravel-root/database/migrations/ directory. This migration file contains class CreateUsersTable.

Here is the updated CreateUsersTable class:


<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('users');
    }
}

Run the following command to execute the migration class


php artisan migrate

The table users will be created on your database laravel.

Creating Model

From Laravel 5.0.0 onwards, there is a User Model class present by default at your-laravel-root/app/User.php.

If it’s not present there, then run the following command to create the Model class ‘User’:


php artisan make:model User

The User model class will be created at your-laravel-root-folder/app/User.php.

You need to add the table name, primary key of the table, etc. in the User class.

Here’s the updated User class:


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The table associated with the model
     *
     * @var string
     */
    protected $table = 'users';
    
    /**
     * Indicates primary key of the table
     *
     * @var bool
     */
    public $primaryKey = 'id';
    
    /**
     * Indicates if the model should be timestamped
     * 
     * default value is 'true'
     * 
     * If set 'true' then created_at and updated_at columns 
     * will be automatically managed by Eloquent
     * 
     * If created_at and updated_at columns are not in your table
     * then set the value to 'false'
     *
     * @var bool
     */
    public $timestamps = true;
    
    /**
     * The attributes that are mass assignable
     *
     * @var array
     */
    protected $fillable = array('name', 'email', 'password', 'created_at', 'updated_at');
    
    /**
     * The attributes that aren't mass assignable
     *
     * @var array
     */
    protected $guarded = array();
    
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = array('password', 'remember_token');
}

Routing

The route file is present at app/Http/routes.php. Here is the code to be put in routes.php for user login and registration:


Route::get('user', array('as' => 'user.index', 'uses' => 'UserController@index'));
Route::get('user/register', array('as' => 'user.register', 'uses' => 'UserController@register'));
Route::post('user/store', array('as' => 'user.store', 'uses' => 'UserController@store'));
Route::get('user/login', array('as' => 'user.login', 'uses' => 'UserController@login'));
Route::post('user/authenticate', array('as' => 'user.authenticate', 'uses' => 'UserController@authenticate'));
Route::get('user/logout', array('as' => 'user.logout', 'uses' => 'UserController@logout'));
Route::get('user/account', array('as' => 'user.account', 'uses' => 'UserController@account'))->middleware('auth');

user.account page is set as auth middleware. Laravel will automatically check for user login when this page is accessed. If the user is not logged in the he/she is redirected to login page. The login redirect path can be adjusted from App\Http\Middleware\Authenticate::handle().

Creating Controller

In Controller class, we write all the logics to fetch data from database table, process it and pass it to views. Controller clasess are saved in app/Http/Controllers directory.

Run the following code to create a UserController controller class.


php artisan make:controller UserController --resource

This will create UserController class at app/Http/Controller/UserController.php. Using --resource will create basic CRUD routes in the User controller class. It will create empty functions named index, create, update, destroy, etc.

In controller functions we call our model class, fetch the data, process it, and pass the data to view file.

Here is the updated UserController class used for this tutorial’s application:


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;

use App\User;

use Session;

use Auth;

class UserController extends Controller
{   
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $user = '';
        return view('user.index', array('user' => $user, 'title' => 'User Page'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function register()
    {
        return view('user.register', array('title' => 'Register'));
    }
        
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, array(
                                'name' => 'required|max:255',
                                'email' => 'required|email|max:255|unique:users',
                                'password' => 'required|min:6|confirmed',
                            )
                        );
        
        //$input = $request->all();        
        //dd($request->email);
        //dd($input); // dd() helper function is print_r alternative
        
        User::create(array(
                        'name' => $request->name, 
                        'email' => $request->email,
                        'password' => bcrypt($request->password),
                    ));
        
        Session::flash('flash_message', 'User registration successful!');

        //return redirect()->back();
        //return redirect('user');
        return redirect()->route('user.login');
    }
    
    /**
     * Show the login form
     *
     * @return \Illuminate\Http\Response
     */
    public function login()
    {
        return view('user.login', array('title' => 'Login'));
    }
    
    /**
     * Authenticate user
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function authenticate(Request $request)
    {       
        if (Auth::attempt(array('email' => $request->email, 'password' => $request->password))) {
            return redirect()->route('user.index');
        } else {
            return redirect()->route('user.login');
        }       
    }
    
    /**
     * Logout user
     *
     * @return \Illuminate\Http\Response
     */
    public function logout() {
        Auth::logout();     
        return redirect()->route('user.login');
    }
    
    /**
     * Show the login form
     *
     * @return \Illuminate\Http\Response
     */
    public function account()
    {
        return view('user.account', array('title' => 'My Account'));
    }    
}

Views

Views are html files present in laravel-root/resources/views directory. Laravel uses Blade templating engine in views which helps to use loops and if/else conditions like PHP in the view html file.

Laravel uses blade templating engine, so the views files should be named as viewname.blade.php.

For this tutorial, we will first create a master template where we include/define the title, header, content and footer. We then extend the master template for other pages of our application. We also display success and error flash message on master template.

Here is our master template (laravel-root/resources/views/layout/master.blade.php):


<html>
    <head>
        <title>@yield('title')</title>
    </head>
    <body>
        <!--
        @section('header')
            <a href="{{ route('news.index') }}">Home</a> | <a href="{{ route('news.create') }}">Add News</a>
        @show
        -->
        @section('header')
            <a href="{{ route('user.index') }}">Home</a>
        
        
        @if(Session::has('flash_message'))
            <div style="color:green; border:1px solid #aaa; padding:4px; margin-top:10px">
                {{ Session::get('flash_message') }}
            </div>
        @endif

        @if($errors->any())
            <div style="color:red; border:1px solid #aaa; padding:4px; margin-top:10px">
                @foreach($errors->all() as $error)
                    {{ $error }}
                @endforeach
            </div>
        @endif
        
        <div>           
            @yield('content')
        </div>
        
        <div>
            Footer @ 2016
        </div>  
    </body>
</html>

resources/views/user/index.blade.php will be extending master.blade.php template and then displaying user info if logged in. If user is not logged in then login and register link is displayed.



@extends('layouts.master')

@section('title', $title)

@section('sidebar')
    @parent
    // you can add something here
@endsection

@section('content') 
    <h1>{{ $title }}</h1>
    
    @if(Auth::check())
        Logged in as:
        
        
            Name: {{ Auth::user()->name }}<br>
            Email: {{ Auth::user()->email }}<br>
            
            <a href="{{ url('user/account') }}">My Account</a> | 
            <a href="{{ url('user/logout') }}">Logout</a> <!-- Can use url() or route() helper functions for URL -->
        
    @else
        
            <a href="{{ route('user.logout') }}">Login</a> | 
            <a href="{{ route('user.register') }}">Register</a> 
        
    @endif
        
@endsection

laravel-root/resources/views/news/register.blade.php



@extends('layouts.master')

@section('title', $title)

@section('sidebar')
    @parent
    // you can add something here
@endsection

@section('content')

    <h1>{{ $title }}</h1>

    {!! Form::open([
        'route' => 'user.store'
    ]) !!}

    <table>
        <tr>
            <td>{!! Form::label('name', 'Name', ['class' => 'control-label']) !!}</td>
            <td>{!! Form::text('name', null, ['class' => 'form-control', 'size' => 40, ]) !!}</td>
        </tr>
        <tr>
            <td>{!! Form::label('email', 'Email', ['class' => 'control-label']) !!}</td>
            <td>{!! Form::email('email', null, ['class' => 'form-control', 'size' => 40, ]) !!}</td>
        </tr>
        <tr>
            <td>{!! Form::label('password', 'Password', ['class' => 'control-label']) !!}</td>
            <td>{!! Form::password('password', null, ['class' => 'form-control', 'size' => 64, ]) !!}</td>
        </tr>       
        <tr>
            <td>{!! Form::label('password_confirmation', 'Confirm Password', ['class' => 'control-label']) !!}</td>
            <td>{!! Form::password('password_confirmation', null, ['class' => 'form-control', 'size' => 64, ]) !!}</td>
        </tr>       
        <tr>
            <td></td>
            <td>{!! Form::submit('Submit', ['class' => 'btn btn-submit']) !!}</td>
        </tr>
    </table>        
    
    {!! Form::close() !!}

@endsection

laravel-root/resources/views/news/login.blade.php



@extends('layouts.master')

@section('title', $title)

@section('sidebar')
    @parent
    // you can add something here
@endsection

@section('content')

    <h1>{{ $title }}</h1>

    {!! Form::open([
        'route' => 'user.authenticate'
    ]) !!}

    <table>     
        <tr>
            <td>{!! Form::label('email', 'Email', ['class' => 'control-label']) !!}</td>
            <td>{!! Form::email('email', null, ['class' => 'form-control', 'size' => 40, ]) !!}</td>
        </tr>
        <tr>
            <td>{!! Form::label('password', 'Password', ['class' => 'control-label']) !!}</td>
            <td>{!! Form::password('password', null, ['class' => 'form-control', 'size' => 64, ]) !!}</td>
        </tr>       
        <tr>
            <td></td>
            <td>{!! Form::submit('Submit', ['class' => 'btn btn-submit']) !!}</td>
        </tr>
    </table>        
    
    {!! Form::close() !!}

@endsection

laravel-root/resources/views/news/account.blade.php



@extends('layouts.master')

@section('title', $title)

@section('sidebar')
    @parent
    // you can add something here
@endsection

@section('content') 
    <h1>{{ $title }}</h1>
    
    Middleware page !!
        
@endsection

Download Source Code from GitHub

Hope this helps. Thanks.

Related posts:

  1. Laravel: Simple CRUD (Add, Edit, Delete, View) [Beginner Tutorial]
  2. CodeIgniter: Add, Edit, Delete, View with Login & Register – MVC CRUD Application
  3. CRUD with Login & Register in PHP & MySQL (Add, Edit, Delete, View)
  4. Very Simple Add, Edit, Delete, View (CRUD) in PHP & MySQL [Beginner Tutorial]
Categories Laravel Tags authentication, laravel, login, PHP, register
Laravel: Simple CRUD (Add, Edit, Delete, View) [Beginner Tutorial]
PHP MySQL: Simple CRUD (Add, Edit, Delete, View) using PDO

About

Mukesh Chapagain Hi, I’m Mukesh Chapagain — a web developer, programmer, and tech enthusiast. Whether you're a beginner or an experienced developer, you’ll find tips, tutorials, and insights to help you navigate the ever-evolving world of technology. Happy coding! 🚀 about...

         

Subscribe via Email



Categories

Most Viewed

  • Very Simple Add, Edit, Delete, View (CRUD) in PHP & MySQL [Beginner Tutorial] - 435,145 views
  • How to Calculate Inverter & Battery Backup Time? - 430,453 views
  • LaTeX: Generate dummy text (lorem ipsum) in your document - 238,158 views
  • GPG: Remove keys from your public keyring? - 203,599 views
  • Magento: How to get attribute name and value? - 189,658 views

Recent Posts

  • Magento: The store that was requested wasn’t found. Verify the store and try again.
  • Magento2: Check Services version on Adobe Cloud Server
  • Magento 2 API: Add Products to Cart & Checkout Place Order
  • Magento 2 API: Create New Customer
  • Magento 2 API: Get Categories

Recent Posts

  • Magento: The store that was requested wasn’t found. Verify the store and try again.
  • Magento2: Check Services version on Adobe Cloud Server
  • Magento 2 API: Add Products to Cart & Checkout Place Order
  • Magento 2 API: Create New Customer
  • Magento 2 API: Get Categories

Most Viewed

  • Very Simple Add, Edit, Delete, View (CRUD) in PHP & MySQL [Beginner Tutorial] - 435,145 views
  • How to Calculate Inverter & Battery Backup Time? - 430,453 views
  • LaTeX: Generate dummy text (lorem ipsum) in your document - 238,158 views
  • GPG: Remove keys from your public keyring? - 203,599 views
  • Magento: How to get attribute name and value? - 189,658 views

Tag Cloud

admin Adobe Commerce api array attribute block category checkout CLI command line crud currency customer Database error extension git Google grid HTML image Javascript Joomla jQuery latex Linux login Magento magento2 magento 2 module MySQL natural language processing NLP nltk nodejs order PHP product python shopping cart template Ubuntu url Wordpress
© 2026 Mukesh Chapagain Blog
Manage Cookie Consent
To provide the best experiences, we use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
  • Manage options
  • Manage services
  • Manage {vendor_count} vendors
  • Read more about these purposes
View preferences
  • {title}
  • {title}
  • {title}