If you wanted to start with Laravel believe me this small article will make you half champion in Laravel. Login, logout, creating, reading, updating, and deleting resources is used mostly in every application.
When you start learning a new programming, I must say you should define some task to be completed like:
1) Login & Logout
2) Simple CRUD operations
Here in this article I will explain basic in laravel like:
1) Login and logout example in Laravel.
2) CRUD operation in Laravel.
3) Routing in Laravel.
4) Messaging in Laravel.
5) How to create middle wares in Laravel.
6) How to use middle wares in Laravel.
You will get answers for all these questions.
Here is the video for demo.
routes/web.php
Here we are defining the routes of the application. I have also created a middleware named as userAuth which don't allow to access the routes for non logged in users.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('/login','Auth\LoginController@getLogin');
Route::get('/register','Auth\RegisterController@getRegister');
Route::post('/register','Auth\RegisterController@postRegister');
Route::post('/login','Auth\LoginController@postLogin');
Route::group(['middleware' => 'userAuth'], function () {
Route::get('/home', 'HomeController@home');
Route::get('/edit/{id}', 'UserController@edit');
Route::get('/delete/{id}', 'UserController@delete');
Route::post('/update', 'UserController@update');
Route::get('/logout', 'Auth\LoginController@logoutUser');
});
|
app/Http/Middleware/UserAuth.php
This is the middleware which I created to check the authenticated users. Here is an example of middleware in laraevl.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class UserAuth
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->guest()) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('login');
}
}
if(Auth::guard($guard)->guest()==false && Auth::user()->role!=1 && Auth::user()->status!=1){
Auth::logout();
return redirect()->guest('login');
}
return $next($request);
}
}
|
You also need to add this middleware into kernel.php
Add following below into $routeMiddleware array in kernel.php
1
|
'userAuth' => UserAuth::class,
|
resources/views/welcome.blade.php
Here is the home page which just contain 2 buttons to register and login the user.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
@extends('layout.header')
@section('content')
<!-- /.login-logo -->
<div class="login-box-body">
<a href="{{url('login')}}"> <button class="btn-primary">Login</button></a>
<a href="{{url('register')}}"> <button class="btn-success">Register</button></a>
</div>
<!-- /.login-box-body -->
</div>
<!-- /.login-box -->
</body>
</html>
@stop
|
we have extended layout header so we also need to create that.
Crete a new directory called layout inside resources/views.
resources/views/layout/header.blade.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Login</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body class="hold-transition login-page">
<div class="login-box">
@yield('content')
|
resources/views/layout/user-headers.blade.php
1
2
|
<a href="{{url('logout')}}">Logout</a>
<a href="{{url('home')}}">Home</a>
|
Now first of all we will register the user.
app/Http/Controllers/Auth/RegisterController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Requests\RegisterRequest;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
class RegisterController extends Controller
{
public function getRegister(){
return view('register');
}
public function postRegister(RegisterRequest $request){
try {
$message = trans('messages.error');
$user = User::create([
'name' => $request['name'],
'email' => $request['email'],
'password' => bcrypt($request['password']),
]);
if (!empty($user)) {
$message = trans('messages.registered');
return redirect('/register')->with('success_msg', $message);
}
} catch (\Exception $e) {
Log::error(__CLASS__ . "::" . __METHOD__ . " " . $e->getMessage() . "on line" . $e->getLine());
}
return redirect('/register')->with('error_msg', $message);
}
}
|
Here in this class we just view the register page and register the user.
I also have created RegisterRequest to validate the post request.
app/Http/Requests/RegisterRequest.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class RegisterRequest extends FormRequest {
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules() {
return [
'name' => 'required',
'email' => 'required|email|unique:users,email',
'password' => 'required'
];
}
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize() {
return true;
}
}
|
Here the view for register form.
resources/views/register.blade.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
@extends('layout.header')
@section('content')
<!-- /.login-logo -->
<div class="login-box-body">
<!-- for validation errors -->
@if(count($errors) > 0)
<div id="error" class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-ban"></i> Error!</h4>
@foreach($errors->all() as $error)
<div class="msg">{{$error}}</div>
@endforeach
</div>
@endif
@if(Session::get('error_msg'))
<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-ban"></i> Error!</h4>
{{Session::get('error_msg')}}
</div>
@elseif(Session::get('success_msg'))
<div class="alert alert-success alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-check"></i> Success !</h4>
{{Session::get('success_msg')}}
</div>
@endif
<p class="login-box-msg">Sign up</p>
<form method="post" action="{{url('register')}}">
{{csrf_field()}}
<div class="form-group has-feedback">
<input type="text" name="name" class="form-control" placeholder="Name" value="{{old('name')}}">
<input type="email" name="email" class="form-control" placeholder="Email" value="{{old('email')}}">
<span class="glyphicon glyphicon-envelope form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<input type="password" name="password" class="form-control" placeholder="Password">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div class="row">
<!-- /.col -->
<div class="col-xs-4">
<button type="submit" class="btn btn-primary btn-block btn-flat">Register</button>
</div>
<!-- /.col -->
</div>
</form>
<a href="{{url('login')}}">Click here to login</a>
</div>
<!-- /.login-box-body -->
</div>
<!-- /.login-box -->
</body>
</html>
@stop
|
Now we have registered the the and now we will login the user.
app/Http/Controllers/Auth/LoginController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
class LoginController extends Controller
{
public function getLogin(){
return view('login');
}
public function postLogin(Request $request){
try {
$message = trans('messages.invalid_login_credentials');
$rememberMe = false;
$user = User::where('email', $request->email)->where('status', 1)->first();
if (!empty($user)) {
//Matching password using hash
$isPasswordMatched = \Hash::check($request->password, $user->password);
if ($isPasswordMatched) {
Auth::loginUsingId($user->id, $rememberMe);
return redirect('/home');
}
}
} catch (\Exception $e) {
Log::error(__CLASS__ . "::" . __METHOD__ . " " . $e->getMessage() . "on line" . $e->getLine());
}
return redirect('/login')->with('error_msg', $message);
}
public function logoutUser(Request $request){
Auth::logout();
return redirect('/login');
}
}
|
Here is the view for login form.
resources/views/login.blade.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
@extends('layout.header')
@section('content')
<!-- /.login-logo -->
<div class="login-box-body">
<!-- for validation errors -->
@if(count($errors) > 0)
<div id="error" class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-ban"></i> Error!</h4>
@foreach($errors->all() as $error)
<div class="msg">{{$error}}</div>
@endforeach
</div>
@endif
@if(Session::get('error_msg'))
<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-ban"></i> Error!</h4>
{{Session::get('error_msg')}}
</div>
@elseif(Session::get('success_msg'))
<div class="alert alert-success alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-check"></i> Success !</h4>
{{Session::get('success_msg')}}
</div>
@endif
<p class="login-box-msg">Sign in</p>
<form method="post" action="{{url('login')}}">
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
<div class="form-group has-feedback">
<input type="email" name="email" class="form-control" placeholder="Email" required>
<span class="glyphicon glyphicon-envelope form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<input type="password" name="password" class="form-control" placeholder="Password" required>
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div class="row">
<!-- /.col -->
<div class="col-xs-4">
<button type="submit" class="btn btn-primary btn-block btn-flat">Sign In</button>
</div>
<!-- /.col -->
</div>
</form>
<a href="{{url('register')}}">Click here to register</a>
</div>
<!-- /.login-box-body -->
</div>
<!-- /.login-box -->
</body>
</html>
@stop
|
app/Http/Controllers/HomeController.php
Here is the home controller which you can access after login.
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<?php
namespace App\Http\Controllers;
use App\User;
class HomeController extends Controller
{
public function home(){
$users = User::select('id','name','email')->get();
return view('home',['users'=>$users]);
}
}
|
Here is the view page for home.
resources/views/home.blade.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
@include('layout.header')
@include('layout.user-headers')
@if(Session::get('error_msg'))
<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-ban"></i> Error!</h4>
{{Session::get('error_msg')}}
</div>
@elseif(Session::get('success_msg'))
<div class="alert alert-success alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-check"></i> Success !</h4>
{{Session::get('success_msg')}}
</div>
@endif
<table class="table table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Action</th>
</tr>
</thead>
<tbody>
@if(!empty($users))
@foreach($users as $user)
<tr>
<td>{{$user->name}}</td>
<td>{{$user->email}}</td>
<td>
<a href="{{'edit'}}/{{$user->id}}"> <button class="btn-success">Edit</button></a>
<a href="{{'delete'}}/{{$user->id}}"> <button class="btn-danger delete">Delete</button></a>
</td>
</tr>
@endforeach
@else
<tr><td colspan="3">No user</td></tr>
@endif
</tbody>
</table>
</div>
<!-- /.login-box-body -->
</div>
<!-- /.login-box -->
</body>
<script>
$(document).on('click', '.delete', function (e) {
var confirmed = confirm("Are you sure you want to delete this record ?");
if (!confirmed)
{
return false;
}
});
</script>
</html>
|
Here is the User controller which contains the edit,update and delete functionality of the user.
app/Http/Controllers/UserController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
<?php
namespace App\Http\Controllers;
use App\Http\Requests\UpdateUserRequest;
use App\User;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function edit(Request $request){
$userDetails = User::select('id','name','email')->where('id',$request->id)->first();
return view('edit',['userDetails'=>$userDetails]);
}
public function update(UpdateUserRequest $request){
$isUpdated = User::where('id',$request->id)->update(['name'=>$request->name,'email'=>$request->email]);
if($isUpdated){
return redirect()->back()->with('success_msg',trans('messages.user_updated'));
}else{
return redirect()->back()->with('error_msg',trans('messages.error_msg'));
}
}
public function delete(Request $request){
$isDeleted = User::where('id',$request->id)->delete();
if($isDeleted){
return redirect()->back()->with('success_msg',trans('messages.user_deleted'));
}else{
return redirect()->back()->with('error_msg',trans('messages.error_msg'));
}
}
}
|
app/Http/Requests/UpdateUserRequest.php
Here is class which validates the user update form data.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class UpdateUserRequest extends FormRequest {
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules() {
return [
'name' => 'required',
'email' => 'required|email'
];
}
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize() {
return true;
}
}
|
Here is the view for edit user form.
resources/views/edit.blade.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
@extends('layout.header')
@section('content')
@include('layout.user-headers')
<!-- /.login-logo -->
<div class="login-box-body">
<!-- for validation errors -->
@if(count($errors) > 0)
<div id="error" class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-ban"></i> Error!</h4>
@foreach($errors->all() as $error)
<div class="msg">{{$error}}</div>
@endforeach
</div>
@endif
@if(Session::get('error_msg'))
<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-ban"></i> Error!</h4>
{{Session::get('error_msg')}}
</div>
@elseif(Session::get('success_msg'))
<div class="alert alert-success alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-check"></i> Success !</h4>
{{Session::get('success_msg')}}
</div>
@endif
<p class="login-box-msg">Update User</p>
<form method="post" action="{{url('update')}}">
{{csrf_field()}}
<div class="form-group has-feedback">
<input type="hidden" name="id" value="{{$userDetails->id}}">
<input type="text" name="name" class="form-control" placeholder="Name" value="{{$userDetails->name}}">
<input type="email" name="email" class="form-control" placeholder="Email" value="{{$userDetails->email}}">
<span class="glyphicon glyphicon-envelope form-control-feedback"></span>
</div>
<div class="row">
<!-- /.col -->
<div class="col-xs-4">
<button type="submit" class="btn btn-primary btn-block btn-flat">Update</button>
</div>
<!-- /.col -->
</div>
</form>
</div>
<!-- /.login-box-body -->
</div>
<!-- /.login-box -->
</body>
</html>
@stop
|
Here is the message file create messages.php inside resources/lang/en directory.
resources/lang/en/messages.php
1
2
3
4
5
6
7
8
9
10
|
<?php
return [
'user_updated' => 'User information has been updated successfully',
'error_msg' => 'Oops! Something went wrong, Please contact to admin',
'registered' => 'User has been registered successfully',
'user_deleted' => 'User has been deleted successfully',
'invalid_login_credentials' => 'Invalid login credentials'
];
|
Laravel Migration or to create the Mysql database users tables.
Set you database connectivity in .env file or config/database.php file.
Then you can create a table via migration command. Here is the command to create the migration.
1
|
php artisan migrate:make create_users_table --table=users --create
|
But Laravel provides users table migration by default so you don't need to run this above command.
you directly got to database/migrations/some_time_stamp_create_users_table.php.
Here is the migration code for our application.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
<?php
use Illuminate\Support\Facades\Schema;
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->smallInteger('role')->default(1);
$table->boolean('status')->default(1);
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
|
Now you just need to run this migration by following below command.
1
|
php artisan migrate
|