/    Sign up×
Bounties /Pin to ProfileBookmark

How to pass data to all views in Laravel?

I have some data that I want to share with all the views of my application, without repeating the code on each return of a view in the controller. I’ve found the snippet <code> View::share(‘data’, [1, 2, 3]); </code>, but I’m not sure where to place this?

to post a answer
Laravel

1 Replies

Copy linkTweet thisAlerts:
@AndrewBentleyAug 11.2022 — One way of achieving this is by doing this in an extension of Laravel's controller and then using that extended controller as a base for other controllers to have access to any shared data:

use Illuminate\Support\Facades\Auth;

class BaseController extends Controller
{
public function __construct()
{
// if we want to share the logged in user with all views, we get the user from Auth and then share it with the view:
$user = Auth::user();
View::share('user', $user);
}
}
@teampl4y4One thing to consider would be making the BaseController abstract so that only the "real" controllers could be created. ```php abstract class BaseController extends Controller ```Feb 07.2023
×

Success!

Help @NathanCruz spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.25,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...