Returning multiple variables with view::share( ) - Laravel 5.1
Asked Answered
A

4

11

I want to return multiple variable to my view.

$currentUser = Auth::user();
$needToBePassed = "Lorem Ipsum"
View::share ( 'currentUser', $currentUser);

This code works fine, however how can if I also want to share $needToBePassed, what should I do?

Is rewriting it is a good practice?

View::share ( 'currentUser', $currentUser);
View::share ( 'needToBePassed', $needToBePassed);
Ahlers answered 4/10, 2015 at 23:34 Comment(0)
M
14

You can pass an array of data,

$data = array(
    'currentUser' => $currentUser,
    'needToBePassed' => $needToBePassed,
);
View::share('data', $data);
Mesmerism answered 4/10, 2015 at 23:41 Comment(6)
but then I'll need to call $data['currentUser'], right?Ahlers
Yeah. Is that a problem?Mesmerism
No, other than I need to change my views. I thought there could be a way to return multiple data like compact. That way, it would be more tidy codeAhlers
You can use extract($data) to extract $currentUser and other elements.Mesmerism
That could be a way too. Also, is it bad if I have multiple view::shares?Ahlers
No, it isn't. You can do it.Mesmerism
L
8

I know the question is already answered, but maybe I can still help a few people by adding this solution. This way you don't have to change all your views.

I was looking for a way to solve this issue without changes all my views.

$currentUser = Auth::user();
$needToBePassed = "Lorem Ipsum";

View::share(['currentUser' => $currentUser, 'needToBePassed' => $needToBePassed]);
Lowminded answered 4/3, 2019 at 12:22 Comment(0)
C
0

You do not need to write mulitple view:share command for variable. you can send all of them in a single command.The view:share basically takes array and it does not matter how you will send this array. you can use the inbuilt function compact to make the code smaller.

$currentUser = Auth::user();
$needToBePassed = "Lorem Ipsum"
View::share(compact('currentUser','needToBePassed'));

Tested and working in Laravel 7 and 8

Cockswain answered 28/7, 2021 at 3:11 Comment(0)
A
0

simply compact your variables as parameters like what you do when you return to a view with compacted data/parameters. Just like what Prakhar Gyawali stated, tested and working in laravel 8.

View()->share(compact('currentUser','needToBePassed'));
Artieartifact answered 17/10, 2022 at 4:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.