Home > Blockchain >  Laravel, Undefined Variable when trying to pass array from controller to views
Laravel, Undefined Variable when trying to pass array from controller to views

Time:08-18

i'm pretty new to Laravel and still trying to figure all of this out. So basically I have an array with a list of movies that I want to pass onto my index.blade.php file. Then show that list in my index file. This is what I have currently.

Route:

Route::get('catalog', 'App\Http\Controllers\CatalogController@getIndex');

Controller:

class CatalogController extends Controller
{
    private $arrayPeliculas = array(...);

    public function getIndex()
    {
        return view('catalog.index', $this->arrayPeliculas);
    }
}

Index:

<body>
    @section('content')
    <div >

        @foreach( $arrayPeliculas as $key => $pelicula )
        <div >

            <a href="{{ url('/catalog/show/' . $key ) }}">
                <img src="{{$pelicula['poster']}}" style="height:200px"/>
                <h4 style="min-height:45px;margin:5px 0 10px 0">
                    {{$pelicula['title']}}
                </h4>
            </a>

        </div>
        @endforeach

    </div>
    @endsection
</body>

I tried doing it a different way that did sort of work

public function getIndex()
    {
        $arrayPeliculas = array(...);
        return view('catalog.index')->with('arrayPeliculas', $arrayPeliculas);
    }

But that doesn't really work for me since I have a few other functions that use this array and when the array is modified it would only be within that specific function. I've looked for similar questions but I don't see what i'm doing wrong. Any help is appreciated, thank you.

CodePudding user response:

You should use this return view('catalog.index', ['arrayPeliculas' => $this->arrayPeliculas]);

  • Related