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);
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!
There are various ways of passing data to views:By using the name array. By using with() function. By using compact() function.
Creating & Rendering Views You may create a view by placing a file with the .blade.php extension in your application's resources/views directory.
public function index()
{
$store = Store::all(); // got this from database model
return view('store')->with('store', $store);
}
You've three options in general.
return view('store')->with('store', $store);
return view('store')->withStore($store);
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.
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'));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With