Register, Login, Password, Logout Laravel 9

Register, Login, Password, Logout Laravel 9

Register, Login, Password, Logout Laravel 9 – Tutorial Register, Login, Password, dan Logout menggunakan Laravel, Bootstrap 5 dan MySQL. Pada artikel sebelumnya sudah membahas tentang Crud User Laravel.

Membuat Project Laravel

Pastikan Anda sudah menginstall composer, kemudian jalankan perintah berikut di command prompt.

composer create-project laravel/laravel laravel-login

Mengatur Database MySQL

Buat database dengan nama laravel_login di http://localhost/phpmyadmin jika Anda menginstall XAMPP untuk server MySQL.

Sesuaikan pengaturan koneksi mysql di project laravel pada file .env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_login
DB_USERNAME=root
DB_PASSWORD=

Sesuaikan DB_HOST, DB_PORT, DB_DATABASE, DB_USERNAME, dan DB_PASSWORD sesuai server MySQL.

Membuat Migration User

Biasanya sudah ada migration users, password_resets, failed_jobs, dan personal_access_tokens yang ada di direktori database/migrations. Anda bisa menggunakan migration users yang sudah disediakan, atau hapus semua migration dan buat migration baru untuk tb_user dengan perintah berikut.

php artisan make:migration create_tb_user_table

Kemudian sesuaikan field pada user migration yang ada di direktori database/migrations sebagai berikut

<?php

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

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

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

Lakukan migration dengan mengetikan perintah berikut.

php artisan migrate

Setelah berhasil menjalankan perintah migrate, maka di database laravel_login akan ada tabel tb_user.

Membuat Model User

Pada laravel 9 sudah berisi model User yang ada di direktori app/models. Jika belum ada atau ingin buat ulang, hapus model User dan gunakan perintah berikut.

php artisan make:model User

Sesuaikan app/models/user.php sebagai berikut.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    protected $table = 'tb_user';
    protected $primaryKey = 'user_id';

    protected $fillable = [
        'name',
        'username',
        'password',
    ];
}

Properti $table untuk mengatur nama tabel di database, jika nama tabel Anda users, tidak usah mengubah properti ini.

Properti $primaryKey untuk mengatur PRIMARY KEY di tabel post, jika primary key Anda id, tidak usah mengubah properti ini.

Properti $fillable untuk mengatur field apa saja yang bisa diinput/ubah ketika melakukan crud di tabel tb_user.

Membuat Controller User

Gunakan perintah berikut untuk membuat controller.

php artisan make:controller UserController

Sesuaikan app/controllers/UserController.php sebagai berikut.

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class UserController extends Controller
{
    public function register()
    {
        $data['title'] = 'Register';
        return view('user/register', $data);
    }

    public function register_action(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'username' => 'required|unique:tb_user',
            'password' => 'required',
            'password_confirm' => 'required|same:password',
        ]);

        $user = new User([
            'name' => $request->name,
            'username' => $request->username,
            'password' => Hash::make($request->password),
        ]);
        $user->save();

        return redirect()->route('login')->with('success', 'Registration success. Please login!');
    }


    public function login()
    {
        $data['title'] = 'Login';
        return view('user/login', $data);
    }

    public function login_action(Request $request)
    {
        $request->validate([
            'username' => 'required',
            'password' => 'required',
        ]);
        if (Auth::attempt(['username' => $request->username, 'password' => $request->password])) {
            $request->session()->regenerate();
            return redirect()->intended('/');
        }

        return back()->withErrors([
            'password' => 'Wrong username or password',
        ]);
    }

    public function password()
    {
        $data['title'] = 'Change Password';
        return view('user/password', $data);
    }

    public function password_action(Request $request)
    {
        $request->validate([
            'old_password' => 'required|current_password',
            'new_password' => 'required|confirmed',
        ]);
        $user = User::find(Auth::id());
        $user->password = Hash::make($request->new_password);
        $user->save();
        $request->session()->regenerate();
        return back()->with('success', 'Password changed!');
    }

    public function logout(Request $request)
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        return redirect('/');
    }
}

Menambahkan Route User

Tambahkan route di routes/web.php seperti berikut.

<?php

use App\Http\Controllers\UserController;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| 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('home', ['title' => 'Home']);
})->name('home');

Route::get('register', [UserController::class, 'register'])->name('register');
Route::post('register', [UserController::class, 'register_action'])->name('register.action');
Route::get('login', [UserController::class, 'login'])->name('login');
Route::post('login', [UserController::class, 'login_action'])->name('login.action');
Route::get('password', [UserController::class, 'password'])->name('password');
Route::post('password', [UserController::class, 'password_action'])->name('password.action');
Route::get('logout', [UserController::class, 'logout'])->name('logout');

Membuat View

View Template

Buat view untuk template dengan bootstrap 5 di direktori resources/views/app.blade.php.

<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <title>@yield('title', $title)</title>
</head>

<body>
    <div class="container">
        <h1>@yield('title', $title)</h1>
        @yield('content')
    </div>
</body>

</html>

View Home

Buat view untuk halaman utama di direktori resources/views/home.blade.php.

@extends('app')
@section('content')
@auth
<p>Welcome <b>{{ Auth::user()->name }}</b></p>
<a class="btn btn-primary" href="{{ route('password') }}">Change Password</a>
<a class="btn btn-danger" href="{{ route('logout') }}">Logout</a>
@endauth
@guest
<a class="btn btn-primary" href="{{ route('login') }}">Login</a>
<a class="btn btn-info" href="{{ route('register') }}">Register</a>
@endguest
@endsection

View Register

Buat view untuk halaman daftar di direktori resources/views/user/register.blade.php.

@extends('app')
@section('content')
<div class="row">
    <div class="col-md-6">
        @if($errors->any())
        @foreach($errors->all() as $err)
        <p class="alert alert-danger">{{ $err }}</p>
        @endforeach
        @endif
        <form action="{{ route('register.action') }}" method="POST">
            @csrf
            <div class="mb-3">
                <label>Name <span class="text-danger">*</span></label>
                <input class="form-control" type="text" name="name" value="{{ old('name') }}" />
            </div>
            <div class="mb-3">
                <label>Username <span class="text-danger">*</span></label>
                <input class="form-control" type="username" name="username" value="{{ old('username') }}" />
            </div>
            <div class="mb-3">
                <label>Password <span class="text-danger">*</span></label>
                <input class="form-control" type="password" name="password" />
            </div>
            <div class="mb-3">
                <label>Password Confirmation<span class="text-danger">*</span></label>
                <input class="form-control" type="password" name="password_confirm" />
            </div>
            <div class="mb-3">
                <button class="btn btn-primary">Register</button>
                <a class="btn btn-danger" href="{{ route('home') }}">Back</a>
            </div>
        </form>
    </div>
</div>
@endsection

View Login

Buat view untuk login di direktori resources/views/user/login.blade.php.

@extends('app')
@section('content')
<div class="row">
    <div class="col-md-6">
        @if(session('success'))
        <p class="alert alert-success">{{ session('success') }}</p>
        @endif
        @if($errors->any())
        @foreach($errors->all() as $err)
        <p class="alert alert-danger">{{ $err }}</p>
        @endforeach
        @endif
        <form action="{{ route('login.action') }}" method="POST">
            @csrf
            <div class="mb-3">
                <label>Username <span class="text-danger">*</span></label>
                <input class="form-control" type="username" name="username" value="{{ old('username') }}" />
            </div>
            <div class="mb-3">
                <label>Password <span class="text-danger">*</span></label>
                <input class="form-control" type="password" name="password" />
            </div>
            <div class="mb-3">
                <button class="btn btn-primary">Login</button>
                <a class="btn btn-danger" href="{{ route('home') }}">Back</a>
            </div>
        </form>
    </div>
</div>
@endsection

View Password

Buat view untuk mengubah password di direktori resources/views/user/password.blade.php.

@extends('app')
@section('content')
<div class="row">
    <div class="col-md-6">
        @if(session('success'))
        <p class="alert alert-success">{{ session('success') }}</p>
        @endif
        @if($errors->any())
        @foreach($errors->all() as $err)
        <p class="alert alert-danger">{{ $err }}</p>
        @endforeach
        @endif
        <form action="{{ route('password.action') }}" method="POST">
            @csrf
            <div class="mb-3">
                <label>Password <span class="text-danger">*</span></label>
                <input class="form-control" type="password" name="old_password" />
            </div>
            <div class="mb-3">
                <label>New Password <span class="text-danger">*</span></label>
                <input class="form-control" type="password" name="new_password" />
            </div>
            <div class="mb-3">
                <label>New Password Confirmation<span class="text-danger">*</span></label>
                <input class="form-control" type="password" name="new_password_confirmation" />
            </div>
            <div class="mb-3">
                <button class="btn btn-primary">Change</button>
                <a class="btn btn-danger" href="{{ route('home') }}">Back</a>
            </div>
        </form>
    </div>
</div>
@endsection

Menjalankan Program

Silahkan gunakan perintah berikut untuk mengaktifkan server laravel.

php artisan serve

Ketikkan alamat sesuai server di browser (http://127.0.0.1:8000/). Hasilnya seperti berikut.

Home Guest
Register
Login
Home Auth
Password

Itulah tutorial membuat Register, Login, Password, dan Logout di Laravel 9. Jika ada yang ditanyakan, silahkan berkomentar.

8 Comments on “Register, Login, Password, Logout Laravel 9”

  • Muhammad Bayu Kurniawan

    says:

    Maaf bang sedikit koreksi untuk codingannya setelah nyobain yang abang punya dan sedikit research:

    Route::get(‘logout’, [UserController::class, ‘logout’])->name(‘logout’);

    Harusnya post method bang bukan get nanti bakal error dia…

    trus di bagian form harus ada

    biar ga error 419

    Terimakasih

    • admin

      says:

      Terimakasih atas masukannya. Tapi kalau logout karena tidak kritikal, menggunakan GET tidak masalah. Kalau ingin method POST, harus buatkan form dengan menambahkan csrf.

    • adin

      says:

      alternatifnya bagaimana.?

      • admin

        says:

        Ikuti saja menggunakan get tidak masalah.

  • errorbang gini pas di pencet login
    Target class [UserController] does not exist.

    tolongin bang

    • admin

      says:

      Tambahkan di bagian atas “uuse App\Http\Controllers\UserController;”

      Kalau menggunakan Extension di Visual Studio Code, pasti otomatis ditambahkan ketika mengetik “UserController”

  • susanto

    says:

    register berhasil, tetapi tidak berhasil login. apanya ya bang

    • admin

      says:

      Apakah ada pesan errornya?

Leave a Comment

Alamat email Anda tidak akan dipublikasikan.

Situs ini menggunakan Akismet untuk mengurangi spam. Pelajari bagaimana data komentar Anda diproses.

To top