Home > Software design >  Laravel can not pass variable from controller to component
Laravel can not pass variable from controller to component

Time:12-29

I can not see my variable in component

Controller

class DigitalContentController extends Controller
{
    public function productsList(){
        $contents = DigitalContent::all();
        return view('pages.digitalContents', compact(['contents']));
    }
}

digitalContents

@extends('layouts.base')

@section('body')

<x-content-card></x-content-card>

@endsection

Component

@foreach ( $contents ?? [] as $item )
    {{ $item->name }}
@endforeach

Even when I echo variable before return view I can see the variable.

class DigitalContentController extends Controller
{
    public function productsList(){
        $contents = DigitalContent::all();
        echo $contents
        return view('pages.digitalContents', compact(['contents']));
    }
}

CodePudding user response:

Because you've to parse the variable to the component. So it should be:

<x-content-card :contents="$contents"></x-content-card>

Don't forget to add contents to your component class

  • Related