05 - Componentes de Blade - Curso Laravel 12 desde cero

 https://www.youtube.com/watch?v=H0tBkWLBK2w&list=PLZ2ovOgdI-kVtF2yQ2kiZetWWTmOQoUSG&index=7

Uso de Componentes en Laravel con Tailwind CSS

Introducción

En este tutorial aprenderás a crear y utilizar componentes en Laravel para optimizar el diseño de tus aplicaciones web. Los componentes te permiten reutilizar elementos como alertas, botones y dropdowns, evitando repetir código y facilitando el mantenimiento.


Requisitos Previos

  • Proyecto Laravel configurado

  • Conocimientos básicos de Blade y Tailwind CSS

  • Terminal o línea de comandos


Paso 1: Incluir Tailwind CSS en el Proyecto

1.1 Obtener el CDN de Tailwind

  1. Dirígete a tailwindcss.com

  2. Accede a la documentación

  3. Selecciona la opción de instalación por CDN

  4. Copia el script proporcionado

1.2 Agregar Tailwind al Layout

Abre tu archivo de layout principal (por ejemplo, resources/views/layouts/app.blade.php) y pega el script debajo de la etiqueta <title>:

html
<script src="https://cdn.tailwindcss.com"></script>

1.3 Verificar la Instalación

Actualiza tu navegador. Si el contenido sin estilos ahora tiene estilos, Tailwind se ha incluido correctamente.


Paso 2: Estructurar la Vista Principal

2.1 Envolver el Contenido

Envuelve tu contenido en un div con las siguientes clases de Tailwind:

html
<div class="max-w-7xl mx-auto px-4">
    <!-- Tu contenido aquí -->
</div>
  • max-w-7xl: Ancho máximo

  • mx-auto: Centrado horizontal

  • px-4: Padding horizontal


Paso 3: Crear un Componente Anónimo de Alerta

3.1 Crear la Carpeta de Componentes

  1. Navega a resources/views/

  2. Crea una carpeta llamada components

  3. Dentro, crea un archivo llamado alert.blade.php

3.2 Definir la Estructura del Componente

Copia el código de una alerta de Tailwind y pégalo en alert.blade.php:

html
<div class="p-4 text-sm rounded-lg bg-blue-100 text-blue-800">
    <span class="font-bold">Info alert!</span> Change a few things up and try submitting again.
</div>

3.3 Usar el Componente

En tu vista (por ejemplo, home.blade.php), reemplaza la alerta por:

html
<x-alert />

Importante: Los componentes deben tener etiqueta de apertura y cierre, o usar la sintaxis de cierre automático.


Paso 4: Hacer el Contenido Variable con Slots

4.1 Definir el Slot Principal

En alert.blade.php, reemplaza el texto por:

html
<div class="p-4 text-sm rounded-lg bg-blue-100 text-blue-800">
    {{ $slot }}
</div>

4.2 Pasar Contenido al Slot

En tu vista:

html
<x-alert>
    Contenido de la alerta
</x-alert>

Paso 5: Usar Slots con Nombre

5.1 Definir un Slot con Nombre

En alert.blade.php:

html
<div class="p-4 text-sm rounded-lg bg-blue-100 text-blue-800">
    <span class="font-bold">{{ $title ?? 'Info alert!' }}</span>
    {{ $slot }}
</div>

5.2 Pasar Contenido al Slot con Nombre

html
<x-alert>
    <x-slot name="title">
        Título de la alerta
    </x-slot>
    Contenido de la alerta
</x-alert>

Paso 6: Pasar Datos con Atributos (Props)

6.1 Definir Props en el Componente

En alert.blade.php, al inicio del archivo:

php
@props(['type' => 'info'])

6.2 Usar el Prop para Cambiar Estilos

php
@php
    $class = match($type) {
        'info' => 'bg-blue-100 text-blue-800',
        'danger' => 'bg-red-100 text-red-800',
        'success' => 'bg-green-100 text-green-800',
        'warning' => 'bg-yellow-100 text-yellow-800',
        'dark' => 'bg-gray-100 text-gray-800',
        default => 'bg-blue-100 text-blue-800',
    };
@endphp

<div class="p-4 text-sm rounded-lg {{ $class }}">
    <span class="font-bold">{{ $title ?? 'Info alert!' }}</span>
    {{ $slot }}
</div>

6.3 Usar el Prop desde la Vista

html
<x-alert type="danger">
    <x-slot name="title">Error</x-slot>
    Ha ocurrido un error.
</x-alert>

Paso 7: Manejar Atributos Adicionales

7.1 Fusionar Clases Adicionales

En alert.blade.php:

php
@props(['type' => 'info'])

@php
    $class = match($type) {
        'info' => 'bg-blue-100 text-blue-800',
        'danger' => 'bg-red-100 text-red-800',
        'success' => 'bg-green-100 text-green-800',
        'warning' => 'bg-yellow-100 text-yellow-800',
        'dark' => 'bg-gray-100 text-gray-800',
        default => 'bg-blue-100 text-blue-800',
    };
@endphp

<div {{ $attributes->merge(['class' => "p-4 text-sm rounded-lg $class"]) }}>
    <span class="font-bold">{{ $title ?? 'Info alert!' }}</span>
    {{ $slot }}
</div>

7.2 Usar Clases Adicionales

html
<x-alert type="success" class="mb-4">
    Operación exitosa.
</x-alert>

Paso 8: Componentes de Clase

8.1 Crear el Componente de Clase

Ejecuta en la terminal:

bash
php artisan make:component Alert2

Esto crea:

  • app/View/Components/Alert2.php

  • resources/views/components/alert2.blade.php

8.2 Definir la Lógica en la Clase

En Alert2.php:

php
<?php

namespace App\View\Components;

use Illuminate\View\Component;

class Alert2 extends Component
{
    public $class;

    public function __construct($type = 'info')
    {
        $this->class = match($type) {
            'info' => 'bg-blue-100 text-blue-800',
            'danger' => 'bg-red-100 text-red-800',
            'success' => 'bg-green-100 text-green-800',
            'warning' => 'bg-yellow-100 text-yellow-800',
            'dark' => 'bg-gray-100 text-gray-800',
            default => 'bg-blue-100 text-blue-800',
        };
    }

    public function render()
    {
        return view('components.alert2');
    }
}

8.3 Simplificar la Vista del Componente

En alert2.blade.php:

html
<div {{ $attributes->merge(['class' => "p-4 text-sm rounded-lg $class"]) }}>
    <span class="font-bold">{{ $title ?? 'Info alert!' }}</span>
    {{ $slot }}
</div>

8.4 Usar el Componente de Clase

html
<x-alert2 type="warning">
    <x-slot name="title">Advertencia</x-slot>
    Ten cuidado con esta acción.
</x-alert2>

Resumen

Tipo de ComponenteVentaja Principal
AnónimoRápido de crear, ideal para diseños simples
De ClaseSepara lógica de la vista, ideal para componentes complejos

Conclusión

Has aprendido a:

  • Incluir Tailwind CSS en Laravel

  • Crear componentes anónimos y de clase

  • Usar slots y props para contenido dinámico

  • Fusionar atributos y clases adicionales

Los componentes te permitirán mantener un código más limpio, reutilizable y fácil de modificar. ¡Practica creando tus propios componentes

Comentarios

Entradas más populares de este blog

02 -Rutas en Laravel

01-04-convencion nombres

1-4-Evolución en PHP Puro-Credenciales en Body/Query String: