Laravel5 how to pass array to view

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')); 
}

Both of the answers provided so far will solve your problem but it's also worth knowing that your original approach of providing $store as the second argument to view() was very nearly correct. What you were missing is that the argument needs to be an array of the variables you want to pass to the view.

I would probably have gone with return view('store', compact('store')); but you could also have used return view('store', ['store' => $store]);.


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.


It works for me. You can use 'compact' like this:

CONTROLLER:

class StoreController extends Controller
{
  public function index()
  {
      $store = Store::all(); // 'don't forget' use App\Driver;
      return view('store', compact('store')); 
  }
}

Don't forget the library: use App\Store;

VIEW:

In the view you have one array with all the data just calling {{ $store }} If you want an specific data use something like:

@foreach($store as $data)
   {{ $data->name }}
@endforeach

Don't forget to use the "Forms & HTML" of Laravel, here is the link of the documentation: https://laravel.com/docs/4.2/html

Tags:

Laravel