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.
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.