skip to Main Content

I have a function which return the view with multiple variable. The code is

HomeController.php

public function profilePage(){
        $data = User::all();
        $book = Library::all();
        return view('page.profile' , compact(array('data', 'book')));
}

profile.blade.php

@include('layouts.sidebar')
.
.
.
 @foreach($book as $Library)
     <tr>
        <td>{{$Library->book}}</td>
        <td>{{$Library->name}}</td>
        <td>{{$Library->author}}</td>
        <td>{{$Library->price}}</td>
    </tr>
 @endforeach

sidebar.blade.php

<div class="info">
  <a href="{{ url ('profile' , $data -> first())}}" class="d-block">{{Auth::user() -> name }}</a>
</div>

When i try to refresh the browser to see the changes. It’ll show error "undefined variable $book"

Illuminate Foundation Bootstrap  HandleExceptions: 176 handleError

on line

addLoop($currentLoopData); foreach($currentLoopData as $Library): $env->incrementLoopIndices(); $loop = $env->getLastLoop(); ?>

Before i added the module to retrieve the data from Library, the code just work fine. So is this the correct approach to pass multiple variable into view?

2

Answers


  1. Try to use this instead, and make sure you are loading the correct blade file, in your case, it’s profile.blade.php inside the page folder.

    public function profilePage(){
        $data = User::all();
        $book = Library::all();
    
        return view('page.profile', [
            'data' => $data,
            'book' => $book,
        ]);
    
    }
    
    Login or Signup to reply.
  2. There are 4 ways for passing data to view:

    1 –

     return view('page.profile' , ['book' => $book, 'data' => $data]);
    

    2 –

    return view('page.profile' , compact('book', 'data'));
    

    3 –

    return view('page.profile')
        ->with('data' => $data)
        ->with('book' => $book);
    

    4 – Not recommended

    return view('page.profile' , get_defined_vars());
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search