Components Tutorial in Laravel 11

 <?php


namespace App\View\Components;

use Closure;
use Illuminate\Contracts\View\View;
use Illuminate\View\Component;

class alert extends Component
{
    public $type;
    public $message;
    public $dismissible;
    protected $types = [
        "success",
        "danger",
        "info"
    ];
    /**
     * Create a new component instance.
     */
    public function __construct(string $type = "info", string $message = "No message", $dismissible = false)
    {
        $this->type = $type;
        $this->message = $message;
        $this->dismissible = $dismissible;
    }

    public function validType()
    {
        return in_array($this->type, $this->types) ? $this->type : "info";
    }

    /**
     * Get the view / contents that represent the component.
     */
    public function render(): View|Closure|string
    {
        return view('components.alert');
    }
}
Above File is app\View\Components\alert File




Below File is resources\views\components\alert File
{{-- <div class="alert alert-{{ $type }}" role="alert">
    {{ $message }}
</div> --}}

<div {{ $attributes->class(["alert-dismissible fade show" => $dismissible])->merge(["class" => "alert alert-".$validType,"role" => $attributes->prepends("alert")]) }}>
    {{ $message }}
    @if($dismissible)
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    @endif
</div>





Below File is resources\views\welcomeTwo File
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Components</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
</head>
<body>
    @php
        $message = "This is just testing";
    @endphp
    {{-- First way as shown below --}}
    <x-alert type="success" message="{{ $message }}"/>  
    {{-- Second way as shown below --}}
    <x-alert type="success" :message="$message"/>
    {{-- Third way as shown below if attribute name and variable name both are same --}}
    <x-alert type="success" dismissible :$message/>
    <x-alert type="danger" dismissible id="firstAlert" class="m-4" role="flash" message="This is error message alert."/>
    <x-alert type="info" message="This is info message alert."/>
</body>
</html>




Below File is routes\web File
<?php

use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return view('welcome');
});

Route::get("/welcomeTwo", function () {
    return view("welcomeTwo");
});





Comments

Popular posts from this blog

Eloquent Many to Many Relationship Tutorial in Laravel 11

Blade Template Tutorial Three Template Inheritance in Laravel 11