How to pass data to partial view file in laravel

Created at 27-Aug-2021 , By samar

How to pass data to partial view file in laravel

In this article, we will see how to solve "How to pass data to partial view file in laravel".

Partial view file is a common file which is used to include in all others layout and individual files in laravel. So here we have the problem of passing the data to partials file by a controller method because we can’t pass data to partials by calling the same code again and again in the controller's method. Which is not a good practice so here we use the AppServiceProvider to do so.
  • Passing data to partials/common file using AppServiceProvider in laravel

    //app\Providers\AppServiceProvider.php
    public function boot()
    {
        \View::composer('partials/header', function ($view) {
            $userDetails= DB::table('users')->select('id','name','email')->first();
            $view->with(['user'=>$userDetails]);
        });
         
    //resources\views\partials\header.blade.php
    {{ $user->name }}
    

    You can pass data to the partial file using appserviceprovider and can display it in the partial view file. Now you can include the partial file in your layout and individual file.

Back to code snippet queries related laravel

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.