How to handle undefined variable when I have to include or extend that blade file in other files

2

There are 2 answers

2
SEYED BABAK ASHRAFI On

You can share your desired data in any blade file by sharing data with those blades.

In your AppServiceProvider

namespace App\Providers;

use Illuminate\Support\Facades\View;

class AppServiceProvider extends ServiceProvider 
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register() 
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot() 
    {
        $user_id = 1; // For example
        $user = \App\Models\User::find($user_id);

        // Share to all blade files
        View::share('user', $user);

        // Or only in a specific blade file
        View::composer('admin.components.topBar', function ($view) use($user) {
            $view->share('user', $user);
        });
    }
}

Now, $user is available in all of your blade files.

0
Locoho On

You can pass the variable to the included view with @include('view.name', ['user' => $user]). You can also check the document about this on https://laravel.com/docs/8.x/blade#including-subviews