Laravel Breeze Installation

Create laravel project

composer create-project laravel/laravel laravel-breeze

cd laravel-breeze

Install laravel breeze package

composer require laravel/breeze --dev

Install laravel breeze

php artisan breeze:install

Update env. file

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=password

Test Application

npm install
npm run build

php artisan migrate
php artisan serve

Laravel Gates

/app/Providers/AuthServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        Gate::define('admin', function($user) {
            return $user->role == 'admin';
        });

        Gate::define('member', function($user) {
            return $user->role == 'member';
        });
    }
}

Via Controller

use Illuminate\Support\Facades\Gate;

if (! Gate::allows('admin')) {
    abort(403);
}

if (Gate::any(['admin', 'member'])) {
    // admin and member can see this
}
 
if (Gate::none(['admin', 'member'])) {
    // admin and member can't see this
}

Gate::authorize('admin');

$this->authorize('admin');

Via middleware

Route::middleware(['auth','can:admin'])->group(function () {
    // admin only
});

Route::get('/admin', function () {
    // admin can access this url
})->middleware('can:admin');

Via blade directive

@can('admin')
   <!-- admin can see this -->
@endcan

@cannot('admin')
   <!-- admin can't see this -->
@endcan

@canany(['admin', 'member'])
   <!-- admin and member can see this -->
@endcanany

Add Migration

php artisan make:migration add_role_column_to_users_table

/database/migrations/xxxx_xx_xx_xxxxxx_add_role_column_to_users_table.php

<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->enum('role', ['admin','member'])->default('admin')->index();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn(['role']);
        });
    }
};

Laravel Eloquent Relationship: One To Many

One To Many

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Post extends Model
{
    public function comments(): HasMany
    {
        return $this->hasMany(Comment::class,'post_id','id');
    }
}

One To Many (Inverse) / Belong To

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Comment extends Model
{
    public function post(): BelongsTo
    {
        return $this->belongsTo(Post::class,'post_id','id');
    }
}

Laravel Query Scope

Local scope

<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
 
class User extends Model
{
    public function scopeActive(Builder $query): void
    {
        $query->where('active', 1);
    }

    public function scopeAdmin($query)
    {
        return $query->where($this->getTable() . '.role', 'admin');
    }
}

Using scope

use App\Models\User;

$user = User::active()->get();
$user = User::admin()->get();

Laravel Model

Artisan command

php artisan make:model Post
# Generate a model and a migration, factory, seeder, and controller...
php artisan make:model Post -mfsc

/app/Models/Post.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;

    protected $table = 'post';
    protected $fillable = ['title'];
    protected $guarded = [];
    protected $connection = 'sqlite';
    protected $primaryKey = 'id';
    protected $keyType = 'string';
    public $incrementing = true;
    public $timestamps = false;
}

Laravel Seeding

Artisan Command

php artisan make:seeder UserSeeder

/database/seeders/UserSeeder.php

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Hash;
use App\Models\User;

class UserSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        User::create([
            'name' => 'Admin',
            'email' => 'admin@host.com',
            'password' => Hash::make('yourPassword'),
            'created_at' => Carbon::now(),
            'updated_at' => Carbon::now(),
        ]);
    }
}

/database/seeders/DatabaseSeeder.php

<?php

namespace Database\Seeders;

// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    public function run(): void
    {
        $this->call(UserSeeder::class);
    }
}

Fake data

User::factory()->count(100)->create();

Laravel Migration

Artisan command

php artisan make:migration create_posts_table

Run migration

php artisan migrate
php artisan migrate:fresh --seed

Rollback migration

php artisan migrate:rollback
php artisan migrate:rollback --step=5

Schema

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
 
Schema::create('users', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->string('code', 50)->unique();
    $table->date('birth_date');
    $table->dateTime('created_at');
    $table->integer('votes');
    $table->decimal('price', 12, 2)->nullable()->default(0);
    $table->enum('status', ['active','inactive'])->index()->default('active');
    $table->foreignId('user_id')->index()->nullable()->default(0);
    $table->longText('description');
    $table->timestamps();
});

Laravel Query Join

Inner Join

$users = DB::table('users')
            ->join('country', 'country.id', '=', 'users.country_id')
            ->select('users.*', 'country.name')
            ->get();

Left / Right Join

$users = DB::table('users')
            ->leftJoin('posts', 'users.id', '=', 'posts.user_id')
            ->get();
 
$users = DB::table('users')
            ->rightJoin('posts', 'users.id', '=', 'posts.user_id')
            ->get();