Home > Back-end >  Pass variable to a component Laravel 9
Pass variable to a component Laravel 9

Time:08-07

I have my main page and in it, I am using component like this and I have a Controller for the main page and from there I am passing variable categories like this:

Main page:

<h1>Hello</h1>
<x-component>

Controller:

public function main_page() {
$categories = Category::all();
return view('main_page', compact('categories');
}

Inside that main page, I can @foreach those variable $categories, but when I want to @foreach it inside my called It shows that variable is not found. How to pass $categories to this component?

CodePudding user response:

You need to add props in your component

<x-component :categories="$categories">

Also you should add this in your component

public $categories;

public function __construct($categories)
{
    $this->categories = $categories;
}

I recommend you read this article

  • Related