Laravel Pass Variables to 'master.blade' - php

I have created a file called 'master.blade.php' that has the menu, and main aspects of my website. I then have files using #extends and #sections. I know how to pass variables using #extends
#extends('master', ['settings' => $settings])
However I am unsure how to pass a variable to the master without having to this on every single page. Is there anyway to do this without having to do it on every page that uses the master? Something like middleware or along those lines?

You can use boot method from AppServiceProvider :
public function boot() {
View::share('settings', 'value');
}
See official documentation here
Or if you want to pass only master :
public function boot()
{
view()->composer('layouts.master', function($view)
{
$view->with('settings', 'value');
});
}

Related

How to make the controller data override view controller in Laravel?

To build a sidebar that has a lot of dynamic data on it I learned about View composers in Laravel. The problem was that View Composers trigger when the view loads, overriding any data from the controller for variables with the same name. According to the Laravel 5.4 documentation though, I achieve what I want with view creators :
View creators are very similar to view composers; however, they are
executed immediately after the view is instantiated instead of waiting
until the view is about to render. To register a view creator, use the
creator method:
From what I understand, this means if I load variables with the same name in the controller and the creator, controller should override it. However this isn't happening with my code. The view composer:
public function boot()
{
view()->creator('*', function ($view) {
$userCompanies = auth()->user()->company()->get();
$currentCompany = auth()->user()->getCurrentCompany();
$view->with(compact('userCompanies', 'currentCompany'));
});
}
And here is one of the controllers, for example:
public function name()
{
$currentCompany = (object) ['name' => 'creating', 'id' => '0', 'account_balance' => 'N/A'];
return view('companies.name', compact('currentCompany'));
}
the $currentCompany variable in question, for example, always retains the value from the creator rather than being overridden by the one from the controller. Any idea what is wrong here?
After some research, I realized my initial assumption that the data from the view creator can be overwritten by the data from the controller was wrong. The creator still loads after the controller somehow. But I found a simple solution.
For those who want to use View composers/creators for default data that can get overwritten, do an array merge between the controller and composer/creator data at the end of the boot() method of the composer/creator, like so:
$with = array_merge(compact('userCompanies', 'currentCompany', 'currentUser'), $view->getData());
$view->with($with);

Share data from a controller to partial footer

In my app, i divided the folders in my view by:
"posts"
"pages"
"partials"
layout.blade.php
In my folder partials i have blade files, like nav.blade.php and footer.blade.php. In my folder "pages", i have files like home.blade.php and some other internal pages.
But now i need to pass a viable from a controller to my footer, since is needed to be shared in all views.
How i pass the variable from my PagesController that manages blade files inside the folder "pages" in the footer?
Example routeS:
Route::get('/', 'PageController#getHome');
Route::get('/registar', 'AuthenticationController#getRegistration');
Route::post('/post/comment', 'CommentController#store');
Route::get('/login', 'AuthenticationController#getLogin');
If i understood correctly, you want to share some data every time particular view is called? If that so, you can do this:
/* App\Providers\AppServiceProvider.php
** Edit the boot function, (dont forget to include View facade) */
public function boot(){
View::composer('path_to_view', function($view)
{
$view->with('variable', $variable); // you can pass array here aswell
});
}
Other way to do this (if you are extending the footer layout from the view you are accessing), is to pass data when you extend the layout, like this:
#extends('footer', ['data' => $data])
If you need to share same variable in multipe view from providers. you can also try to this
public function boot()
{
//set view path in array
View::composer(['path_to_view1', 'path_to_view2'], function ($view) {
$view->with('variableName', $variableName);
});
}

Adding in a variable via route with static route laravel

I want to be able to add a variable to a route that directs to a controller.
The only way I've seen it done is if the route itself is dynamic. However, in my case, I want a static url that will send a static variable to a controller. The reason for which is that there will be two static routes that will use the same controller in a different way via variables.
I am having trouble finding this in the documentation.
All I have found is this
Route::get('posts/{post}/comments/{comment}', function ($postId, $commentId) {
I want to do the same but have {comment} and {post} but two variables is sent to the controllers.
Any help would be awesome!
Forexample:
Route::get('posts/{post}/comments/{comment}', ['as'=> 'viewComment', 'uses'=>'PostController#viewComment']);
Controller:
public function viewComment ($post, $comment)
{
dd($post.'/'.$comment);
}

Laravel - How to pass variable to layout partial view

I have a partial view in master layout which is the navigation bar. I have a variable $userApps. This variable checks if the user has enabled apps (true), if enabled then I would like to display the link to the app in the navigation bar.
homepage extends master.layout which includes partials.navbar
My code in the navbar.blade.php is this:
#if ($userApps)
// display link
#endif
However I get an undefined variable error. If I use this in a normal view with a controller it works fine after I declare the variable and route the controller to the view. I dont think I can put a controller to a layout since I cant route a controller to a partial view, so how do I elegantly do this?
What version of Laravel you use? Should be something like this for your case:
#include('partials.navbar', ['userApps' => $userApps])
Just for a test purpose, I did it locally, and it works:
routes.php
Route::get('/', function () {
// passing variable to view
return view('welcome')->with(
['fooVar' => 'bar']
);
});
resources/views/welcome.blade.php
// extanding layout
#extends('layouts.default')
resources/views/layouts/default.blade.php
// including partial and passing variable
#include('partials.navbar', ['fooVar' => $fooVar])
resources/views/partials/navbar.blade.php
// working with variable
#if ($fooVar == 'bar')
<h1>Navbar</h1>
#endif
So the problem must be in something else. Check your paths and variable names.
The other answers did not work for me, or seem to only work for older versions. For newer versions such as Laravel 7.x, the syntax is as follows.
In the parent view:
#include('partial.sub_view', ['var1' => 'this is the value'])
In the sub view:
{{ $var1 }}
I have gone through all the answers but below is the best way to do because you can also run queries in serviceProvider.
You need to create a separate service or you can use AppServiceProvider
<?php
namespace App\Providers;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* #return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
View::composer('layouts.admin-layout', function ($view) {
$view->with('name', 'John Doe');
});
}
}
In your layout
{{$name}}
This approach is very simple:
In parent view :
#include('partial.sub_view1', ['This is value1' => $var1])
In sub view :
{{ $var1 }}
You can use view composer to send your variable to partial view.
Check the laravel documentation on laravel.com about view composer.
Also you can check the following link that will help you resolve this problem.
https://scotch.io/tutorials/sharing-data-between-views-using-laravel-view-composers

Laravel - How to pass data to include

So essentially all of my views are using the header.blade.php since I am including it in my master layout. I need to pass data to the header on every single view. Is there a way to pass data just to the include rather than passing the data for the header in each view?
You don't need to do that, but you can:
All variables that are available to the parent view will be made
available to the included view. Even though the included view will
inherit all data available in the parent view, you may also pass an
array of extra data to the included view:
#include('view.name', ['some' => 'data'])
One option if you're trying to send data only to the included view is to use a view composer. They will fire even in the case of trying to prepare a view for #include
view()->composer('header', function($view) {
$view->with('data', 'some data');
});
actually the very best and faster method of sharing data to all views could be just using the
AppServiceProvider
instead of Jeff's answer you can use the share method instead of the composer method and achieve your goal faster.
Just pass the data you want in the boot method of the AppServiceProvider like following
public function boot()
{
View::share('key', 'value');
}
for more check this

Categories