Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel5 how to pass array to view

Tags:

laravel

I am confuse as how to pass variable from controller to view. I know there is a lot about this already on stockoverflow but unable to find one that works, please point me in the right direction. Thank you.

CONTROLLER

 class StoreController extends Controller

 {
    public function index()
    {
        $store = Store::all(); // got this from database model
        return view('store', $store); 
    }
 {

VIEW

// try a couple of differnt things nothing works 

print_r($store); 
print_r($store[0]->id);
print_r($id); 
like image 311
aahhaa Avatar asked Feb 10 '16 21:02

aahhaa


People also ask

How do you pass an array in blade?

If you want to pass the array itself, you have to tell blade: Hey, take this array and make it available in the view by the given name: return View::make('hello')->with('data', $data); Now you have the whole array available in your view by the variable $data . Awesome!

How do I transfer data from one view to another in laravel?

There are various ways of passing data to views:By using the name array. By using with() function. By using compact() function.

How to add view in Laravel?

Creating & Rendering Views You may create a view by placing a file with the .blade.php extension in your application's resources/views directory.


2 Answers

public function index()
{
  $store = Store::all(); // got this from database model

  return view('store')->with('store', $store); 
}

You've three options in general.

  1. return view('store')->with('store', $store);

  2. return view('store')->withStore($store);

  3. return view('store')->with(compact('store'));

1.Creates a variable named store which will be available in your view and stores the value in the variable $store in it.

2.Shorthand for the above one.

3.Also a short hand and it creates the same variable name as of the value passing one.

Now in your view you can access this variable using

{{ $store->name }}

it will be same for all 3 methods.

like image 82
Jilson Thomas Avatar answered Oct 14 '22 00:10

Jilson Thomas


Try this

public function index()
{
    return view('store', ['store' => Store::all()]); 
}

Then you can access $store in your review.

Update: If you have your variable defined already in your code and want to use the same name in your view you can also use compact method.

Example:

public function index()
{
    $store = Store::all();

    return view('store', compact('store')); 
}
like image 22
Can Celik Avatar answered Oct 14 '22 01:10

Can Celik