What is Components? 

Components are the reusable segment or layout which we can use inside the laravel application. It helps in time-saving and escapes the repetition of code.


Created a component by using a command.

php artisan make:component NameOfComponent


And this command provides a View in resources/views/components/nameofcomonent.blade.php and a PHP file in app/View/Components/NameOfComponent.php.



Once your component has been generated, it may be rendered using its name:<x-nameofcomonent/>


Example

Create Header component

php artisan make:component Header



once you execute this command automatically, it will generate our component files 

app/Components/
┣ Header.php

resources/views/components/
┣ header.blade.php

header.blade.php

<div>
    <p>Header component view</p>
</div>


Create views

Create views to render your component


views/
┣ index.blade.php
┣ signin.blade.php

index.blade.php

<x-header/>
<h1>Header view</h1>


 signin.blade.php

<x-header/>
<h1>Signin View</h1>


Create routes

routes/web.php

Route::view('/signin', 'signin');
Route::view('/', 'index');


go through the URL and see the output of the component is everywhere in the views



We can also pass variables in the component via attributes

<x-header : test="test value"/>


Pass the data

app/Components/
┣ Header.php

Header.php

<?php

namespace App\View\Components;

use Illuminate\View\Component;

class Header extends Component
{
    /**
     * Create a new component instance.
     *
     * @return void
     */
    
    public $test;
    public function __construct($test)
    {
        //
        $this->test = $test;
    }

    /**
     * Get the view / contents that represent the component.
     *
     * @return \Illuminate\Contracts\View\View|string
     */
    public function render()
    {
        return view('components.header');
    }
}