Home > Net >  Passing data from controller to view in Laravel - Display the error message Undefined variable
Passing data from controller to view in Laravel - Display the error message Undefined variable

Time:09-25

I have faced the issue for Undefined variable: images - Error message. Please check the below codes. Please support me.

'Route::get('partials/recent-gallery','ImageGalleryController@recentview');'

'public function recentview()
{
    $images = ImageGallery::all();
    return view('partials.recent-gallery', ['images' => $images]);          
}'

---Home Page '@include('partials/recent-gallery')'

---- View page-----recent-gallery.blade.php------

'@if($images->count())
    @foreach($images as $image)  
        {{ $image->galley_image }}
@endforeach  
@endif'

-------------------ERROR---------------
$images is undefined

CodePudding user response:

The steps to pass data to subview is by passing the data from the parent (In your case it is the homepage) to the subview (recent-gallery) with the help of the blade syntax.

You must first pass the data to the Homepage from your function which initialize your homepage route and pass the image data for your subview.


public function viewHomePage()
{
   $images = ImageGallery::all();  
 
   // passing your image data to the homepage not to your subview

   return view('home', ['images' => $images]); 
}

You do not have to have a separate route for your subview as it is a subview. Pass the data you passed along from your Homepage view function to the subview by blade syntax @include('partials/recent-gallery', ['images' => $images]). Notice we have not routed a subview in web.php or have a controller function to pass image data.

home.blade.php


<!-- homepage content -->

@include('partials/recent-gallery', ['images' => $images])

Then you can access the image data inside your subview with the parameter $images. You can check your passing data with dd() method and passing the parameters dd($images) so you can debug.

partials/recent-gallery.blade.php

@if($images->count())
    @foreach($images as $image)  
        {{ $image->galley_image }}
    @endforeach  
@endif
  • Related