Ilmu Coding Ilmucoding.com - Merupakan situs yang membantu Anda belajar coding lebih mudah, nyaman, interaktif dan profesional. Belajar sekarang di ilmu coding. GRATIS

Simple Auth Laravel 7 Tutorial With Example

7 min read

Simple Auth Laravel 7 Tutorial With Example
Loading...

Simple Auth Laravel 7 Tutorial With Example. Step by step to create simple login features, register and logout with Laravel 7 + Bootstrap also program example and source code.

Laravel include UI package that can handle auth brilliant.

… in 6 and 7 version, they provide artisan ui that can generate and can choose three choice, which is Bootstrap, React Js or Vue Js.

But, even provided as sophisticated as possible, beginner will confuse to use it.

Moreover there are features that may unused.

That’s way, in this chance, I will share how to create simple auth in Laravel 7.

… in practice, this tutorial will helped by Library Auth belong to Laravel.

Loading...

Do you curious about it?

Read Also: Tutorial Custom Helper di Laravel 7

Let’s follow step by step how to create simple auth in laravel 7 + bootstrap bellow.

Step by Step to Create Auth Features in Laravel 7

As preparation step, there are things that we must know:

First, minimum for installing php version 7.2

Second, already installed supporting web server like XAMPP, Laragon, Nginx and so on.

Third, text editor. Here I use Visual Studio Code which is open source apps.

Loading...

Let’s we began!

Step 1 – Install and Composer Check

If you not yet to install composer, please download here.

Then, make sure composer installed well.

The way, open command line.

Type composer.

If it installed well, will be appear as bellow:

Next, we will install Laravel 7 with composer that have been install.

Loading...

Step 2 – Install Laravel 7 with Composer

Way to install Laravel 7 very easy if we use composer.

composer create-project --prefer-dist laravel/laravel:^7.0 laravel_auth

But before it, make it sure your internet is stable.

Please wait until the process is done.

Step 3 – Trial to Run Laravel 7

Before we get into main discussion, let we run first.

Please go to project directory.

Can use terminal or Visual Studio Code

… and don’t forget to activate your web server.

Loading...

Now, if you ready, you can run the terminal and type command bellow:

cd laravel_auth
// then
php artisan serve

Look at pitcure below:

… if use terminal in Visual Studio Code, directly type this:

Now we can ensure the result with type URL bellow:

http://127.0.0.1:8000

The result:

Step 4 – Prepare Database

While installation, Laravel 7 provide table user schema that we can directly use.

Even the model is available

Loading...

So, No need for us to create schema and model.

… and to manage all of it, we can apply in .env.

Attention for this pic:

Cool, right?!

Just use it.

So, we create database which name laravel17_auth.

Up to you want put it in PHPMyadmin or other tools.

Loading...

Then, open .env file and setting database configuration.

Search this code:

DB_DATABASE=laravel

Edit tobe:

Loading...
DB_DATABASE=laravel7_auth

Database preparation is done.

Step 5 – Table Preparation

First, turn off server of PHP Artisan, then run again the server.

It because in Laravel 7 not automatic read env if there is change.

DB_DATABASE=laravel7_auth

Oke, now tables is formed.

Loading...

Step 6 – Create Login Route, Register and Logout

Please open web.php file in routes/web.php directory.

Add this code:

<?php
 
use Illuminate\Support\Facades\Route; 
 
Route::get('/', 'AuthController@showFormLogin')->name('login');
Route::get('login', 'AuthController@showFormLogin')->name('login');
Route::post('login', 'AuthController@login');
Route::get('register', 'AuthController@showFormRegister')->name('register');
Route::post('register', 'AuthController@register');
 
Route::group(['middleware' => 'auth'], function () {
 
    Route::get('home', 'HomeController@index')->name('home');
    Route::get('logout', 'AuthController@logout')->name('logout');
 
});

Explanation:

Program code above created to appear login form, login process, register form, and register process.

Then, completed by auth middleware so that home and logout can be access when already login.

Step 7 – Create Auth Controller

Type this command in terminal to create AuthController:

php artisan make:controller AuthController

Then, open AuthController.php file in app/Http/Controllers directory.

Loading...

Here the code:

<?php
 
namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
 
use Illuminate\Support\Facades\Auth;
use Validator;
use Hash;
use Session;
use App\User;
 
 
class AuthController extends Controller
{
    public function showFormLogin()
    {
        if (Auth::check()) { // true sekalian session field di users nanti bisa dipanggil via Auth
            //Login Success
            return redirect()->route('home');
        }
        return view('login');
    }
 
    public function login(Request $request)
    {
        $rules = [
            'email'                 => 'required|email',
            'password'              => 'required|string'
        ];
 
        $messages = [
            'email.required'        => 'Email wajib diisi',
            'email.email'           => 'Email tidak valid',
            'password.required'     => 'Password wajib diisi',
            'password.string'       => 'Password harus berupa string'
        ];
 
        $validator = Validator::make($request->all(), $rules, $messages);
 
        if($validator->fails()){
            return redirect()->back()->withErrors($validator)->withInput($request->all);
        }
 
        $data = [
            'email'     => $request->input('email'),
            'password'  => $request->input('password'),
        ];
 
        Auth::attempt($data);
 
        if (Auth::check()) { // true sekalian session field di users nanti bisa dipanggil via Auth
            //Login Success
            return redirect()->route('home');
 
        } else { // false
 
            //Login Fail
            Session::flash('error', 'Email atau password salah');
            return redirect()->route('login');
        }
 
    }
 
    public function showFormRegister()
    {
        return view('register');
    }
 
    public function register(Request $request)
    {
        $rules = [
            'name'                  => 'required|min:3|max:35',
            'email'                 => 'required|email|unique:users,email',
            'password'              => 'required|confirmed'
        ];
 
        $messages = [
            'name.required'         => 'Nama Lengkap wajib diisi',
            'name.min'              => 'Nama lengkap minimal 3 karakter',
            'name.max'              => 'Nama lengkap maksimal 35 karakter',
            'email.required'        => 'Email wajib diisi',
            'email.email'           => 'Email tidak valid',
            'email.unique'          => 'Email sudah terdaftar',
            'password.required'     => 'Password wajib diisi',
            'password.confirmed'    => 'Password tidak sama dengan konfirmasi password'
        ];
 
        $validator = Validator::make($request->all(), $rules, $messages);
 
        if($validator->fails()){
            return redirect()->back()->withErrors($validator)->withInput($request->all);
        }
 
        $user = new User;
        $user->name = ucwords(strtolower($request->name));
        $user->email = strtolower($request->email);
        $user->password = Hash::make($request->password);
        $user->email_verified_at = \Carbon\Carbon::now();
        $simpan = $user->save();
 
        if($simpan){
            Session::flash('success', 'Register berhasil! Silahkan login untuk mengakses data');
            return redirect()->route('login');
        } else {
            Session::flash('errors', ['' => 'Register gagal! Silahkan ulangi beberapa saat lagi']);
            return redirect()->route('register');
        }
    }
 
    public function logout()
    {
        Auth::logout(); // menghapus session yang aktif
        return redirect()->route('login');
    }
 
 
}

Explanation:

Laravel provide library that can handle Authentication.

We can use use Illuminate\Support\Facades\Auth to make the facility beneficial.

Beside that, we also use Hash Library that available in Laravel to change password that we registered into encryption

… this use to save reason.

Then, in this line we use to check whether user already login or not yet.

Loading...

If done, so user will go to main page.

if (Auth::check()) {
    return redirect()->route('home');
}

Step 8 – Create Home Controllers

Please type code bellow to create HomeController.php:

php artisan make:controller HomeController

Then open HomeController.php file in app/Http/Controllers.

Type this code:

<?php
 
namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
 
class HomeController extends Controller
{
    public function index()
    {
        return view('home');
    }
}

Explanation:

In this controller I not wrap it with constructor, that in general it contain with load middleware auth.

Because we applied filter in Route, so it unnecessary.

Loading...

Step 9 – Create Login View Page

Please create new file named login.blade.php and save in resources/views directory.

Here the program:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Login</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body>
    <div class="container">
        <div class="col-md-4 offset-md-4 mt-5">
            <div class="card">
                <div class="card-header">
                    <h3 class="text-center">Form Login</h3>
                </div>
                <form action="{{ route('login') }}" method="post">
                @csrf
                <div class="card-body">
                    @if(session('errors'))
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            Something it's wrong:
                            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                <span aria-hidden="true">×</span>
                            </button>
                            <ul>
                            @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                            @endforeach
                            </ul>
                        </div>
                    @endif
                    @if (Session::has('success'))
                        <div class="alert alert-success">
                            {{ Session::get('success') }}
                        </div>
                    @endif
                    @if (Session::has('error'))
                        <div class="alert alert-danger">
                            {{ Session::get('error') }}
                        </div>
                    @endif
                    <div class="form-group">
                        <label for=""><strong>Email</strong></label>
                        <input type="text" name="email" class="form-control" placeholder="Email">
                    </div>
                    <div class="form-group">
                        <label for=""><strong>Password</strong></label>
                        <input type="password" name="password" class="form-control" placeholder="Password">
                    </div>
                </div>
                <div class="card-footer">
                    <button type="submit" class="btn btn-primary btn-block">Log In</button>
                    <p class="text-center">Belum punya akun? <a href="{{ route('register') }}">Register</a> sekarang!</p>
                </div>
                </form>
            </div>
        </div>
    </div>
</body>
</html>

Save.

Step 10 – Create View Register Page

Please create new file name register.blade.php and save in resources/views directory.

Here the code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Register</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body>
    <div class="container">
        <div class="col-md-4 offset-md-4 mt-5">
            <div class="card">
                <div class="card-header">
                    <h3 class="text-center">Form Register</h3>
                </div>
                <form action="{{ route('register') }}" method="post">
                @csrf
                <div class="card-body">
                    @if(session('errors'))
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            Something it's wrong:
                            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                <span aria-hidden="true">×</span>
                            </button>
                            <ul>
                            @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                            @endforeach
                            </ul>
                        </div>
                    @endif
                    <div class="form-group">
                        <label for=""><strong>Nama Lengkap</strong></label>
                        <input type="text" name="name" class="form-control" placeholder="Nama Lengkap">
                    </div>
                    <div class="form-group">
                        <label for=""><strong>Email</strong></label>
                        <input type="text" name="email" class="form-control" placeholder="Email">
                    </div>
                    <div class="form-group">
                        <label for=""><strong>Password</strong></label>
                        <input type="password" name="password" class="form-control" placeholder="Password">
                    </div>
                    <div class="form-group">
                        <label for=""><strong>Konfirmasi Password</strong></label>
                        <input type="password" name="password_confirmation" class="form-control" placeholder="Password">
                    </div>
                </div>
                <div class="card-footer">
                    <button type="submit" class="btn btn-primary btn-block">Register</button>
                    <p class="text-center">Sudah punya akun? <a href="{{ route('login') }}">Login</a> sekarang!</p>
                </div>
                </form>
            </div>
        </div>
    </div>
</body>
</html>

Save.

Step 11 – Create Home View Page

Please create new file name home.blade.php and save in resources/views directory.

Loading...

Here the code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Dashboard</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body>
    <div class="container">
        <div class="col-md-12 mt-5">
            <div class="card">
                <div class="card-header">
                    <h3>Dashboard</h3>
                </div>
                <div class="card-body">
                    <h5>Selamat datang di halaman dashboard, <strong>{{ Auth::user()->name }}</strong></h5>
                    <a href="{{ route('logout') }}" class="btn btn-danger">Logout</a>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

Step 12 – Testing for Auth Laravel 7 Login, Register, and Logout

Please type this command to testing the program:

php artisan serve

Then, open browser and type URL:

http://localhost:8000

The result:

Simple Auth Laravel 7 Tutorial With Example - Login

… And if you don’t have account, please register first

Click the register link, so the result is:

Simple Auth Laravel 7 Tutorial With Example - Register

Then, if success to register and login, so it will appear dashboard page like this:

Loading...
Simple Auth Laravel 7 Tutorial With Example - Home

Now, if you want to logout from the apps, please press logout button and it will appear to login page again

Extra Explanation

Alhamdulillah, we arrive in the end of this tutorial to make Auth Laravel 7 features like login, register, and logout

So, what next?

There are many article that I will write.

So, please stay tune in this web ilmucoding.com

Thanks alot.

Loading...
Loading...

Ilmu Coding Ilmucoding.com - Merupakan situs yang membantu Anda belajar coding lebih mudah, nyaman, interaktif dan profesional. Belajar sekarang di ilmu coding. GRATIS

Leave a Reply

Your email address will not be published. Required fields are marked *

Jika terbantu dengan artikel ini, silahkan share, beri komentar dan "klik" 1 kali pada iklan ya.