Laravel ‐ Chapters 11‐12 - pierre-akhrass/Lavarel-Docs GitHub Wiki

Chapter 11: Blade Components in Laravel

What is a Blade Component?

A Blade component is a reusable piece of UI in Laravel. It allows you to create custom HTML tags with optional data binding and logic. Components help keep your views clean and modular.


Creating a Component

Generate a component using Artisan:

php artisan make:component Alert

This creates:

  • app/View/Components/Alert.php
  • resources/views/components/alert.blade.php

Using a Component

Invoke your component in a Blade view:

<x-alert type="danger" message="Something went wrong!" />

Inside alert.blade.php:

<div class="alert alert-{{ $type }}">
    {{ $message }}
</div>

Passing Data to Components

Blade automatically binds values passed as props:

<x-alert :type="$type" :message="$message" />

Component class:

public function __construct(public string $type, public string $message) {}

What is a $slot in Laravel Components?

In Laravel Blade components, a slot is a placeholder for the content that you pass into a component when you use it.


Think of it Like This:

Imagine you have a reusable component called <x-alert>.

You want the look of the alert to always be the same (colors, layout), but the message inside the alert should change.

That dynamic message goes into the slot.


Step-by-Step Example

1. Component Blade file: resources/views/components/alert.blade.php

<div class="alert alert-{{ $type }}">
    {{ $slot }}
</div>

Here, {{ $slot }} will be replaced with whatever content you place inside the <x-alert> tag.

2. Using the Component in a View:

<x-alert type="success">
    Your changes have been saved successfully!
</x-alert>

3. Rendered Output:

<div class="alert alert-success">
    Your changes have been saved successfully!
</div>

So the text Your changes have been saved successfully! is what fills the $slot.


Why Use Slots?

  • You create a consistent layout or design once.
  • You reuse it with different content in different places.
  • Clean separation of structure (component) and content (slot).

Named Slots (Advanced)

You can also define multiple custom areas using named slots.

Component Blade file:

<div class="card">
    <div class="card-header">
        {{ $title }}
    </div>
    <div class="card-body">
        {{ $slot }}
    </div>
</div>

Usage:

<x-card>
    <x-slot:title>
        My Card Title
    </x-slot:title>

    This is the body of the card.
</x-card>

{{ $title }} becomes My Card Title, and {{ $slot }} becomes This is the body...



Organizing Components

You can nest components into folders:

resources/views/components/dashboard/button.blade.php

Usage:

<x-dashboard.button>Click me</x-dashboard.button>

Anonymous Components

You can create a component without a class:

resources/views/components/card.blade.php

Usage:

<x-card title="Post Title">
    Post body content here.
</x-card>

Component view:

<div class="card">
  <h1>{{ $title }}</h1>
  {{ $slot }}
</div>

Why Use Blade Components?

  • Reusability – Write once, reuse anywhere
  • Separation of concerns – Logic vs. layout
  • Improved readability – Semantic and clean
  • Maintainability – Easier updates and DRY code

Real-World Use

Used for:

  • Navigation links
  • Buttons
  • Alerts
  • Modals
  • Layouts

Chapter 12: Seeders and Factories

Laravel's database seeding and model factories are powerful tools that allow you to populate your database with dummy data. This is essential during development and testing to simulate real-world usage.


What are Seeders and Factories?

  • Seeders are classes that insert records into your database.
  • Factories define the blueprint for generating model instances with random/fake data using the Faker library.

Creating a Seeder

Create a new seeder class:

php artisan make:seeder UserSeeder

Location: database/seeders/UserSeeder.php

Example:

use Illuminate\Database\Seeder;
use App\Models\User;

class UserSeeder extends Seeder
{
    public function run(): void
    {
        User::factory()->count(10)->create();
    }
}

Creating a Factory

Generate a factory linked to a model:

php artisan make:factory UserFactory --model=User

Location: database/factories/UserFactory.php

Example:

use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

class UserFactory extends Factory
{
    public function definition(): array
    {
        return [
            'name' => $this->faker->name(),
            'email' => $this->faker->unique()->safeEmail(),
            'email_verified_at' => now(),
            'password' => bcrypt('password'),
            'remember_token' => Str::random(10),
        ];
    }
}

Running Seeders

Run a specific seeder:

php artisan db:seed --class=UserSeeder

Run all seeders defined in DatabaseSeeder.php:

php artisan db:seed

Refresh database and seed:

php artisan migrate:fresh --seed

DatabaseSeeder File

Located in database/seeders/DatabaseSeeder.php. Use it to call multiple seeders:

public function run(): void
{
    $this->call([
        UserSeeder::class,
        PostSeeder::class,
    ]);
}

Factory States and Overrides

Define specialized versions (states) of a model:

public function admin()
{
    return $this->state(fn(array $attributes) => [
        'role' => 'admin',
    ]);
}

Override attributes directly:

User::factory()->create([
    'email' => '[email protected]'
]);

Seeding Relationships

Seed users with posts and comments:

User::factory()
    ->count(10)
    ->has(
        Post::factory()
            ->count(3)
            ->hasComments(5)
    )
    ->create();

Ensure factories like PostFactory and CommentFactory define user_id/post_id foreign keys.


Testing Use Case

Use factories in tests:

public function test_post_creation()
{
    $post = Post::factory()->create();
    $this->assertDatabaseHas('posts', [ 'id' => $post->id ]);
}

Reset and Reseed Database

php artisan migrate:fresh --seed

This clears all tables, reruns migrations, and executes seeders—perfect for testing and development.


⚠️ **GitHub.com Fallback** ⚠️