Variable pass in components in laravel

Variable pass in components in laravel

A. Router

Route::get('/', function () {
return view('index', ['data' => 'Hi my name is paan']);
});

B. index.blade.php

<x-cart type="text" name="username" label="Username" :data="$data" />
<x-cart type="password" name="password" label="Password" :data="$data" />

C. cart.php  // class based file of cart component

<?php

namespace App\View\Components;

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

class Cart extends Component
{
/**
* Create a new component instance.
*/

public $type;
public $name;
public $label;
public $data;

public function __construct($type, $name, $label, $data)
{
$this->type = $type;
$this->name = $name;
$this->label = $label;
$this->data = $data;
}

/**
* Get the view / contents that represent the component.
*/
public function render(): View|Closure|string
{
return view('components.cart');
}
}

D. cart.blade.php

<div class="form-control">
<label>{{$label}}</label>
<input type="{{$type}}" name="{{$name}}" class="form-control" />

</div>

{{$data}}

Leave a Reply