8

I just started shifting to Laravel 5 from Symfony and I am wondering how to pass multiple arrays from my controller to my view.

I am trying to use PHP's compact() function but I am unable to properly get them in the view.

$users = Users::all();
$projects = Projects::all();
$foods = Foods::all();

return ('controller.view', compact('users','projects','foods'));

What is the best for me to be able to transfer all these array of objects to my view.

Any help would be greatly appreciated.

Thanks!

2 Answers 2

17

You're missing call to the view method in your example

return view('controller.view', compact('users','projects','foods'));

That said, the rest of the syntax is correct.

In your view you can access those variables as you would normally. If you're using blade for example.

In resources/views/controller/view.blade.php

@foreach ($users as $user)
    {{$user->property}}
@endforeach

If you're not using blade.

In resources/views/controller/view.php

<?php
foreach ($users as $user) {
    echo $user->property;
}
?>
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry I had a typo when I was making the original post. My code had return view() in it but for some reason the compact was failing.
7

I found the answer to my question.

return view('controller.view', array('users' => $users,
               'projects' => $projects ,'foods' => $foods)

And in blade I just normally accessed them through the foreach iteration.

1 Comment

Hey Ben thanks for the very fast and insightful reply. Unfortunately for some reason, the compact() function was failing on the view. I was also for sure that it should be able to handle it. Passing the variables through an array worked for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.