3

I have an action method which has in its body multiple Variables something like this :-

$bus=Bus::all();
$user=User::all();
$employer=employer::all();

what am doing to return those variables objects to the view is using code like this

return view('create')->with(compact('bus', $bus))->with(compact('user', $user))->with(compact('employer', $employer));

is there a way a method or something to return this objects at once without the need for all of this code some thing like

return view('create')->($user,$bus,$emp);

just example of what i want .

3

3 Answers 3

7

you can create an array like this

$data['bus']=Bus::all();
$data['user']=User::all();
$data['employer']=employer::all();
return view('create',['data'=>$data]);
Sign up to request clarification or add additional context in comments.

6 Comments

nice one :) but does this will return it in array as i need it to be return as json if i would make it for an api or something ?
@NasrAdin.if you print data it contain key value pair.so even in api its working properly
Yeah sure sry forgot :) thk again . @iCoders
@NasrAdin.glad to here .answer is helped
so bro when i want to access one of thie objects in the view , rather than using the variable for example $user->id i would use $user['data']->id ? thanks in advance
|
6

You have few options here.

First approach is:

Use with() and pass an array explicitly:

return view('create')->with('data', [
    'bus' => $bus, 
    'user' => $user,
    'employer' => $employer
]);

Use with() and list your variables in compact():

return view('create')->with('data', compact('bus','user','employer'));

Your objects would be accessible in the view like an associative array $data with keys 'bus','user' and 'employer'.

Another approach is:

Pass an array as a second argument to view() function:

return view('create', [
    'bus' => $bus, 
    'user' => $user,
    'employer' => $employer
]);

Pass an compact() function (which would create an array like in the previous example behind the scenes) as a second argument to view() function:

return view('create', compact('bus','user','employer'));

If you use it this manner you will get three variables $bus, $user and $employer accessible in your view.

Comments

2

You can do pretty much what you're after with

return view('create', compact('bus', 'user', 'employer'));

or do the $data option above

Comments

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.