Passing default data to every views in Laravel
To pass default data to every views View::share('data',$data); can be used. You need to make a BaseController class. This class will extend Larvael’s controller and sets many global functions. After creating BaseController class other controllers will extend from this controller.
class BaseController extends Controller{
public function __construct()
{
//its just a dummy data object.
$user = User::all();
View::share('user', $user);
}
}
You can also use a filter for setting up something to use in all views for the entire application.
App::before(function($request){
// Set up global user object for views
View::share('user', User::all());
});
An alternative way is to use a middleware.
Route::group(['middleware' => 'SomeMiddleware'], function(){// routes
});
class SomeMiddleware {
public function handle($request)
{
\View::share('user', auth()->user());
}
}
Create an App\Http\ViewComposers directory and create the Service provider file with the below code and add the Service Provider under config/app.php provider’s list.
namespace App\Providers;use Illuminate\Support\ServiceProvider;
class ViewComposerServiceProvider extends ServiceProvider {
public function boot() {
view()->composer("ViewName","App\Http\ViewComposers\TestViewComposer");
}
}
Create a test file for ViewComposer.
namespace App\Http\ViewComposers;use Illuminate\Contracts\View\View;
class TestViewComposer {
public function compose(View $view) {
$view->with('ViewComposerTestVariable', "Calling with View Composer Provider");
}
}
Now add the below code to the View in which you want to display the data.
Here you are... {{$ViewComposerTestVariable}}
Change the code in the Service Provider if you want the data to be displayed in all views.
namespace App\Providers;use Illuminate\Support\ServiceProvider;
class ViewComposerServiceProvider extends ServiceProvider {
public function boot() {
view()->composer('*',"App\Http\ViewComposers\TestViewComposer");
}
}
Comments
0 comments
Please Sign in or Create an account to Post Comments