How to append data to default laravel view after application creation [duplicate] - php

How can I in Laravel 5 make global variable which will be available in all Blade templates?

Option 1:
You can use view::share() like so:
<?php namespace App\Http\Controllers;
use View;
//You can create a BaseController:
class BaseController extends Controller {
public $variable1 = "I am Data";
public function __construct() {
$variable2 = "I am Data 2";
View::share ( 'variable1', $this->variable1 );
View::share ( 'variable2', $variable2 );
View::share ( 'variable3', 'I am Data 3' );
View::share ( 'variable4', ['name'=>'Franky','address'=>'Mars'] );
}
}
class HomeController extends BaseController {
//if you have a constructor in other controllers you need call constructor of parent controller (i.e. BaseController) like so:
public function __construct(){
parent::__construct();
}
public function Index(){
//All variable will be available in views
return view('home');
}
}
Option 2:
Use a composer:
Create a composer file at app\Composers\HomeComposer.php
NB: create app\Composers if it does not exists
<?php namespace App\Composers;
class HomeComposer
{
public function compose($view)
{
//Add your variables
$view->with('variable1', 'I am Data')
->with('variable2', 'I am Data 2');
}
}
Then you can attached the composer to any view by doing this
<?php namespace App\Http\Controllers;
use View;
class HomeController extends Controller{
public function __construct(){
View::composers([
'App\Composers\HomeComposer' => ['home'] //attaches HomeComposer to home.blade.php
]);
}
public function Index(){
return view('home');
}
}
Option 3:
Add Composer to a Service Provider, In Laravel 5 I prefer having my composer in App\Providers\ViewServiceProvider
Create a composer file at app\Composers\HomeComposer.php
Add HomeComposer to App\Providers\ViewServiceProvider
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use View;
use App\Composers\HomeComposer;
use Illuminate\Support\Facades\Blade;
class ViewServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* #return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
//add to all views
view()->composer('*', HomeComposer::class);
//add to only home view
//view()->composer('home', HomeComposer::class);
}
}

Create a new Service Provider as suggested in here
Add your new Service Provider to the configuration file (config/app.php).
In the boot method of your new Service Provider use:
View::share( 'something_cool', 'this is a cool shared variable' );
Now you are ready to use $something_cool in all of your views.
Hope this helps.

Searching for solution of the same problem and found the best solution in Laravel documentation. Just use View::share in AppServiceProvider like this:
View::share('key', 'value');
Details here.

You can do this with view composers. View composers are executed when a template is loaded. You can pass in a Closure with additional functionality for that view. With view composers you can use wildcards. To make a view composer for every view just use a *.
View::composer('*', function($view)
{
$view->with('variable','Test value');
});
You can also do this without a closure as you can see in the docs.
View::composer('*', 'App\Http\ViewComposers\ProfileComposer');
The profile composer class must have a compose method.
View composers are executed when a view is rendered. Laravel has also view creators. These are executed when a view is instantiated.
You can also choose to use a BaseController with a setupLayout method. Then every view which you will load is loaded through the setupLayout method which adds some additional data. However, by using view composers you're pretty sure that the code is executed. But with the BaseController approach you've more flexibility because you can skip the loading of the extra data.
EDIT: As mentioned by Nic Gutierrez you can also use view share.

Also, you can do this in the Route.php file:
view()->share('variableName', $variable);

I would rather use middleware with the view() facade helper. (Laravel 5.x)
Middleware is easier to mantain and does not make a mess in the controllers class tree.
Steps
Create the Middleware
/app/Http/Middleware/TimezoneReset.php
To create a middleware you can run php artisan make:middleware GlobalTimeConfig
share() the data you need shared
<?php
namespace App\Http\Middleware;
use Closure;
class GlobalTimeConfig
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$time_settings = [
'company_timezone' => 'UTC',
'company_date_format' => 'Y-m-d H:i:s',
'display_time' => true,
];
view()->share('time_settings', $time_settings);
return $next($request);
}
}
Register the newly created middleware
Add the middleware to your middleware route group as per example below
/app/Http/Kernel.php
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\GlobalTimeConfig::class,
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
Access data from templates
Access the data from any template with the given key in the View::share() method call
eg.:
Company timezone: {{ $time_settings['company_timezone'] }}
EDIT:
Nic Gutierrez's Service Provider answer might be a better (or the best) solution.

and you can give array not just View::share('key', 'value');
can put array like View::share(['key'=>'value','key'=>'value'])

You can add in Controller.php file:
use App\Category;
And then:
class Controller extends BaseController {
public function __construct() {
$categories = Category::All();
\View::share('categories', $categories);
}
}

you can flash it into the session, you can define it in the .env file (static vars)

Related

Passing data for all views in Laravel [duplicate]

I want to have some default data accessible in all views in my Laravel 5 application.
I have tried to search for it but only find results for Laravel 4. I have read the documentation 'Sharing Data With All Views' here but I can't understand what to do. Where should the following code be placed?
View::share('data', [1, 2, 3]);
Thanks for your help.
This target can achieve through different method,
1. Using BaseController
The way I like to set things up, I make a BaseController class that extends Laravel’s own Controller, and set up various global things there. All other controllers then extend from BaseController rather than Laravel’s Controller.
class BaseController extends Controller
{
public function __construct()
{
//its just a dummy data object.
$user = User::all();
// Sharing is caring
View::share('user', $user);
}
}
2. Using Filter
If you know for a fact that you want something set up for views on every request throughout the entire application, you can also do it via a filter that runs before the request — this is how I deal with the User object in Laravel.
App::before(function($request)
{
// Set up global user object for views
View::share('user', User::all());
});
OR
You can define your own filter
Route::filter('user-filter', function() {
View::share('user', User::all());
});
and call it through simple filter calling.
Update According to Version 5.*
3. Using Middleware
Using the View::share with middleware
Route::group(['middleware' => 'SomeMiddleware'], function(){
// routes
});
class SomeMiddleware {
public function handle($request)
{
\View::share('user', auth()->user());
}
}
4. Using View Composer
View Composer also help to bind specific data to view in different ways. You can directly bind variable to specific view or to all views. For Example you can create your own directory to store your view composer file according to requirement. and these view composer file through Service provide interact with view.
View composer method can use different way, First example can look alike:
You could create an App\Http\ViewComposers directory.
Service Provider
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class ViewComposerServiceProvider extends ServiceProvider {
public function boot() {
view()->composer("ViewName","App\Http\ViewComposers\TestViewComposer");
}
}
After that, add this provider to config/app.php under "providers" section.
TestViewComposer
namespace App\Http\ViewComposers;
use Illuminate\Contracts\View\View;
class TestViewComposer {
public function compose(View $view) {
$view->with('ViewComposerTestVariable', "Calling with View Composer Provider");
}
}
ViewName.blade.php
Here you are... {{$ViewComposerTestVariable}}
This method could help for only specific View. But if you want trigger ViewComposer to all views, we have to apply this single change to ServiceProvider.
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class ViewComposerServiceProvider extends ServiceProvider {
public function boot() {
view()->composer('*',"App\Http\ViewComposers\TestViewComposer");
}
}
Reference
Laravel Documentation
For Further Clarification Laracast Episode
If still something unclear from my side, let me know.
You can either create your own service provider (ViewServiceProvider name is common) or you can use the existing AppServiceProvider.
In your selected provider, put your code in the boot method.
public function boot() {
view()->share('data', [1, 2, 3]);
}
This will make a $data variable accessible in all your views.
If you rather want to use the facade instead of the helper, change view()-> to View:: but don't forget to have use View; at the top of your file.
I found this to be the easiest one. Create a new provider and user the '*' wildcard to attach it to all views. Works in 5.3 as well :-)
<?php
namespace App\Providers;
use Illuminate\Http\Request;
use Illuminate\Support\ServiceProvider;
class ViewServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
* #return void
*/
public function boot()
{
view()->composer('*', function ($view)
{
$user = request()->user();
$view->with('user', $user);
});
}
/**
* Register the application services.
*
* #return void
*/
public function register()
{
//
}
}
The best way would be sharing the variable using View::share('var', $value);
Problems with composing using "*":
Consider following approach:
<?php
// from AppServiceProvider::boot()
$viewFactory = $this->app->make(Factory::class);
$viewFacrory->compose('*', GlobalComposer::class);
From an example blade view:
#for($i = 0; $i<1000; $i++)
#include('some_partial_view_to_display_i', ['toDisplay' => $i])
#endfor
What happens?
The GlobalComposer class is instantiated 1000 times using
App::make.
The event composing:some_partial_view_to_display_i is handled
1000 times.
The compose function inside the GlobalComposer class is called 1000 times.
But the partial view some_partial_view_to_display_i has nothing to do with the variables composed by GlobalComposer but heavily increases render time.
Best approach?
Using View::share along a grouped middleware.
Route::group(['middleware' => 'WebMiddleware'], function(){
// Web routes
});
Route::group(['prefix' => 'api'], function (){
});
class WebMiddleware {
public function handle($request)
{
\View::share('user', auth()->user());
}
}
Update
If you are using something that is computed over the middleware pipeline you can simply listen to the proper event or put the view share middleware at the last bottom of the pipeline.
In the documentation:
Typically, you would place calls to the share method within a service
provider's boot method. You are free to add them to the
AppServiceProvider or generate a separate service provider to house
them.
I'm agree with Marwelln, just put it in AppServiceProvider in the boot function:
public function boot() {
View::share('youVarName', [1, 2, 3]);
}
I recommend use an specific name for the variable, to avoid confussions or mistakes with other no 'global' variables.
You have two options:
1. Share via ‍Boot function in App\Providers\AppServiceProvider:
public function boot()
{
view()->share('key', 'value');
}
And access $key variable in any view file.
Note: Remember that you can't access current Session, Auth, Route data here. This option is good only if you want to share static data. Suppose you want to share some data based on the current user , route, or any custom session variable you won't be able to do with this.
2. Use of a helper class:
Create a helper class anywhere in your application and register it in Alias array in app.php file in config folder.
'aliases' => [
...,
'Helper' => App\HelperClass\Helper::class,
],
and create Helper.php in HelperClass folder within App folder:
namespace App\HelperClass;
class Helper
{
public static function Sample()
{
//Your Code Here
}
}
and access it anywhere like Helper::Sample().
You will not be restricted here to use Auth, Route, Session, or any other classes.
The documentation is hear https://laravel.com/docs/5.4/views#view-composers but i will break it down
Look for the directory app\Providers in the root directory of your application and create the file ComposerServiceProvider.php and copy and past the text below into it and save it.
<?php
namespace App\Providers;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
class ComposerServiceProvider extends ServiceProvider
{
/**
* Register bindings in the container.
*
* #return void
*/
public function boot()
{
// Using class based composers...
View::composer(
'profile', 'App\Http\ViewComposers\ProfileComposer'
);
// Using Closure based composers...
View::composer('dashboard', function ($view) {
//
});
}
/**
* Register the service provider.
*
* #return void
*/
public function register()
{
//
}
}
From the root of your application open Config/app.php and look for the Providers section in the file and copy and past this 'App\Providers\ComposerServiceProvider', to the array.
By doing this, we have created the Composer Service Provider. When you run your application with the view Profile like so http://yourdomain/something/profile, the service provider ComposerServiceProvider is called and the class App\Http\ViewComposers\ProfileComposer is instantiated calling the method Composer due to the code below inside the boot method or function.
// Using class based composers...
View::composer(
'profile', 'App\Http\ViewComposers\ProfileComposer'
);
If you refresh your application you will get an error because the class App\Http\ViewComposers\ProfileComposer does not exist yet. Now lets create it.
Go to the directory path app/Http
Create the directory called ViewComposers
Create the file ProfileComposer.php.
class ProfileComposer
{
/**
* The user repository implementation.
*
* #var UserRepository
*/
protected $users;
/**
* Create a new profile composer.
*
* #param UserRepository $users
* #return void
*/
public function __construct(UserRepository $users)
{
// Dependencies automatically resolved by service container...
$this->users = $users;
}
/**
* Bind data to the view.
*
* #param View $view
* #return void
*/
public function compose(View $view)
{
$view->with('count', $this->users->count());
}
}
Now go to your view or in this case Profile.blade.php and add
{{ $count }}
and that will show the count of users on the profile page.
To show the count on all pages change
// Using class based composers...
View::composer(
'profile', 'App\Http\ViewComposers\ProfileComposer'
);
To
// Using class based composers...
View::composer(
'*', 'App\Http\ViewComposers\ProfileComposer'
);
1) In (app\Providers\AppServiceProvider.php)
// in boot function
view()->composer('*', function ($view) {
$data = User::messages();
$view->with('var_messages',$data);
});
2) in Your User Model
public static function messages(){ // this is just example
$my_id = auth()->user()->id;
$data= Message::whereTo($my_id)->whereIs_read('0')->get();
return $data; // return is required
}
3) in Your View
{{ $var_messages }}
I think that the best way is with View Composers. If someone came here and want to find how can do it with View Composers way, read my answer => How to share a variable across all views?
Laravel 5.6 method: https://laravel.com/docs/5.6/views#passing-data-to-views
Example, with sharing a model collection to all views (AppServiceProvider.php):
use Illuminate\Support\Facades\View;
use App\Product;
public function boot()
{
$products = Product::all();
View::share('products', $products);
}
The documentation is here https://laravel.com/docs/5.4/views#view-composers but i will break it down
1.Look for the directory Providers in your root directory and create the for ComposerServiceProvider.php with content
Inside your config folder you can create a php file name it for example "variable.php" with content below:
<?php
return [
'versionNumber' => '122231',
];
Now inside all the views you can use it like
config('variable.versionNumber')
I created ViewServiceProvider for passing data for multiple views, in Laravel 8
Creating app/Provides/ViewServiceProvider.php file.
class ViewServiceProvider extends ServiceProvider
{
public function register()
{
//
}
public function boot()
{
//for user views(resources/views/user/*)
View::composer(['user.*'], function ($view) {
$f_user = Auth::user();
$f_platform = 'user';
$view->with(compact( 'f_user', 'f_platform'));
});
// for admin views(resources/views/admin/*)
View::composer('admin.*', function ($view) {
$f_admin = Auth::guard('admin')->user();
$f_platform = 'admin';
$view->with(compact( 'f_admin', 'f_platform'));
});
//for all views(resources/views/*)
View::composer('*', function ($view) {
$f_something = [];
$view->with(compact('f_something'));
});
}
}
Register ViewServiceProvider in config/app.php
'providers' => [
...
App\Providers\ViewServiceProvider::class,
],
Using in blades
{{ $f_user }}
{{ $f_platform }}
{{ $f_something }}
{{ $f_admin }}
{{ $f_platform }}
{{ $f_something }}
for example you can return list of all tables in database to the all views of Controller
like this :
public function __construct()
{
$tables = DB::select('SHOW TABLES'); // returns an array of stdObjects
view()->share('tables', $tables);
}
In Laravel 5 and above versions , you can edit boot function in
AppServiceProvider.php to access variable in all views
public function boot()
{
\View::composer('*', function($view){
$view->with('key', 'value');
});
}
"Key" represents the name of the variable which you want to set, so that you can use it later in any .blade.php file and "value" represents the value represented by the variable... For Example :
//setting user role to be accessed by all blade.php files
public function boot(){
//
View::composer('*', function($view){
view->with('role', Auth::user()->infouser->role);
});
}
If are you using Laravel 8 you can do this like that,
class Controller extends BaseController{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
public function __construct(){
$categories = Category::where('show_menu', '=', 1)->where('status', '=', 'approved')->get();
view()->share('categories', $categories);
}}

How to use a php variable in all blades files in Laravel-5.4?

How can i use a variable in all blades page ?
Controller
public function index1(){
$article='var-1';
return view('index',compact('article');
}
index.blade.php
{{ $article }}
Result of index.blade.php
var-1
index2.blade.php
{{ $article }}
Result of index2.blade.php
Not Found
It is my problem to find out a way to use one variable and use that in my all *.blade.php files.
How can i fix this ?
You can create a Composer and pass the data on the main view.
Example:
class MyComposer
{
public function compose(View $view)
{
$article='var-1';
$view->with(['article' => article]);
}
}
and call the class in your AppServiceProvider class inside the boot() function like this:
view()->composer('layouts.app', MyComposer::class);
layouts.app is the main view which is included on your views
If you need more info see the docs
You can Pass data to all views easily.
Just add the following in your AppServiceProvider.php inside the boot() method:
View::share('key', 'value');
You can share a piece of data with all views that are rendered by your application using the view facade's share method. Typically, you should place calls to share within a service provider's boot method. You are free to add them to the AppServiceProvider or generate a separate service provider to house them:
<?php
namespace App\Providers;
use Illuminate\Support\Facades\View;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
View::share('key', 'value');
}
/**
* Register the service provider.
*
* #return void
*/
public function register()
{
//
}
}

Laravel 5.2 'Master Layout' Variable passing

So here is what I'm trying to achieve. I have a default blade template default.blade.php which is extended by all of my child views.
Within my default.blade.php i have a foreach loop which expresses some 'global' options to the user, and example of which is below.
#foreach ($projects as $p)
<li><a href='$p->project_uid'>{{ $p->project_name }}</a></li>
#endforeach
So to achieve this I'm having to pass the $projects variable via the view('viewname', $data) or via View::share('projects', $projects); in my Controller __construct()
Is there a better way for me to do this on a global sense so that the above calls don't need to be made?
One option i am aware of is calling a Model function from within my view, but this defies the concept of MVC so is not ideal.
Any guidance on the subject would be appreciated, Thanks.
Edit 1
So i tried the ViewComposer solution but ran into a couple of problems.
Below is my Composer & the Service Provider Register.
Config/app.php
App\Providers\ComposerServiceProvider::class,
ComposerServiceProvider
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class ComposerServiceProvider extends ServiceProvider {
/**
* Register bindings in the container.
*
* #return void
*/
public function boot() {
// Using class based composers...
view ()->composer ( 'default', 'App\Http\ViewComposers\MasterComposer' );
}
/**
* Register the service provider.
*
* #return void
*/
public function register() {
//
}
}
MasterComposer
<?php
namespace App\Http\ViewComposers;
use Illuminate\View\View;
use App\Repositories\UserRepository;
use Sentinel;
use ProjectUsers;
class MasterComposer
{
protected $users;
public function __construct(ProjectUsers $users)
{
$uid = Sentinel::getUser()->id;
$this->users = ProjectUsers::where("user_id", '=', $uid)->get();
}
public function compose(View $view)
{
$view->with('projects', $this->users);
}
}
Am i missing something obvious as it doesn't seem like the Composer is being loaded at all.
Edit 2
Fixed it myself. Realised that within the ComposerServiceProvider i need to specify a full path to my view like so.
view ()->composer ( 'admin/layouts/default', 'App\Http\ViewComposers\MasterComposer' );
Now it Works :D
Yes, you do this with View Composer.
View composers are callbacks or class methods that are called when a
view is rendered. If you have data that you want to be bound to a view
each time that view is rendered, a view composer can help you organize
that logic into a single location.
Bind that data to defualt.blade.php view, like:
public function compose(View $view)
{
$data = .... // Get data here.
$view->with('projects', $data);
}

How to pass data to all views in Laravel 5?

I want to have some default data accessible in all views in my Laravel 5 application.
I have tried to search for it but only find results for Laravel 4. I have read the documentation 'Sharing Data With All Views' here but I can't understand what to do. Where should the following code be placed?
View::share('data', [1, 2, 3]);
Thanks for your help.
This target can achieve through different method,
1. Using BaseController
The way I like to set things up, I make a BaseController class that extends Laravel’s own Controller, and set up various global things there. All other controllers then extend from BaseController rather than Laravel’s Controller.
class BaseController extends Controller
{
public function __construct()
{
//its just a dummy data object.
$user = User::all();
// Sharing is caring
View::share('user', $user);
}
}
2. Using Filter
If you know for a fact that you want something set up for views on every request throughout the entire application, you can also do it via a filter that runs before the request — this is how I deal with the User object in Laravel.
App::before(function($request)
{
// Set up global user object for views
View::share('user', User::all());
});
OR
You can define your own filter
Route::filter('user-filter', function() {
View::share('user', User::all());
});
and call it through simple filter calling.
Update According to Version 5.*
3. Using Middleware
Using the View::share with middleware
Route::group(['middleware' => 'SomeMiddleware'], function(){
// routes
});
class SomeMiddleware {
public function handle($request)
{
\View::share('user', auth()->user());
}
}
4. Using View Composer
View Composer also help to bind specific data to view in different ways. You can directly bind variable to specific view or to all views. For Example you can create your own directory to store your view composer file according to requirement. and these view composer file through Service provide interact with view.
View composer method can use different way, First example can look alike:
You could create an App\Http\ViewComposers directory.
Service Provider
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class ViewComposerServiceProvider extends ServiceProvider {
public function boot() {
view()->composer("ViewName","App\Http\ViewComposers\TestViewComposer");
}
}
After that, add this provider to config/app.php under "providers" section.
TestViewComposer
namespace App\Http\ViewComposers;
use Illuminate\Contracts\View\View;
class TestViewComposer {
public function compose(View $view) {
$view->with('ViewComposerTestVariable', "Calling with View Composer Provider");
}
}
ViewName.blade.php
Here you are... {{$ViewComposerTestVariable}}
This method could help for only specific View. But if you want trigger ViewComposer to all views, we have to apply this single change to ServiceProvider.
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class ViewComposerServiceProvider extends ServiceProvider {
public function boot() {
view()->composer('*',"App\Http\ViewComposers\TestViewComposer");
}
}
Reference
Laravel Documentation
For Further Clarification Laracast Episode
If still something unclear from my side, let me know.
You can either create your own service provider (ViewServiceProvider name is common) or you can use the existing AppServiceProvider.
In your selected provider, put your code in the boot method.
public function boot() {
view()->share('data', [1, 2, 3]);
}
This will make a $data variable accessible in all your views.
If you rather want to use the facade instead of the helper, change view()-> to View:: but don't forget to have use View; at the top of your file.
I found this to be the easiest one. Create a new provider and user the '*' wildcard to attach it to all views. Works in 5.3 as well :-)
<?php
namespace App\Providers;
use Illuminate\Http\Request;
use Illuminate\Support\ServiceProvider;
class ViewServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
* #return void
*/
public function boot()
{
view()->composer('*', function ($view)
{
$user = request()->user();
$view->with('user', $user);
});
}
/**
* Register the application services.
*
* #return void
*/
public function register()
{
//
}
}
The best way would be sharing the variable using View::share('var', $value);
Problems with composing using "*":
Consider following approach:
<?php
// from AppServiceProvider::boot()
$viewFactory = $this->app->make(Factory::class);
$viewFacrory->compose('*', GlobalComposer::class);
From an example blade view:
#for($i = 0; $i<1000; $i++)
#include('some_partial_view_to_display_i', ['toDisplay' => $i])
#endfor
What happens?
The GlobalComposer class is instantiated 1000 times using
App::make.
The event composing:some_partial_view_to_display_i is handled
1000 times.
The compose function inside the GlobalComposer class is called 1000 times.
But the partial view some_partial_view_to_display_i has nothing to do with the variables composed by GlobalComposer but heavily increases render time.
Best approach?
Using View::share along a grouped middleware.
Route::group(['middleware' => 'WebMiddleware'], function(){
// Web routes
});
Route::group(['prefix' => 'api'], function (){
});
class WebMiddleware {
public function handle($request)
{
\View::share('user', auth()->user());
}
}
Update
If you are using something that is computed over the middleware pipeline you can simply listen to the proper event or put the view share middleware at the last bottom of the pipeline.
In the documentation:
Typically, you would place calls to the share method within a service
provider's boot method. You are free to add them to the
AppServiceProvider or generate a separate service provider to house
them.
I'm agree with Marwelln, just put it in AppServiceProvider in the boot function:
public function boot() {
View::share('youVarName', [1, 2, 3]);
}
I recommend use an specific name for the variable, to avoid confussions or mistakes with other no 'global' variables.
You have two options:
1. Share via ‍Boot function in App\Providers\AppServiceProvider:
public function boot()
{
view()->share('key', 'value');
}
And access $key variable in any view file.
Note: Remember that you can't access current Session, Auth, Route data here. This option is good only if you want to share static data. Suppose you want to share some data based on the current user , route, or any custom session variable you won't be able to do with this.
2. Use of a helper class:
Create a helper class anywhere in your application and register it in Alias array in app.php file in config folder.
'aliases' => [
...,
'Helper' => App\HelperClass\Helper::class,
],
and create Helper.php in HelperClass folder within App folder:
namespace App\HelperClass;
class Helper
{
public static function Sample()
{
//Your Code Here
}
}
and access it anywhere like Helper::Sample().
You will not be restricted here to use Auth, Route, Session, or any other classes.
The documentation is hear https://laravel.com/docs/5.4/views#view-composers but i will break it down
Look for the directory app\Providers in the root directory of your application and create the file ComposerServiceProvider.php and copy and past the text below into it and save it.
<?php
namespace App\Providers;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
class ComposerServiceProvider extends ServiceProvider
{
/**
* Register bindings in the container.
*
* #return void
*/
public function boot()
{
// Using class based composers...
View::composer(
'profile', 'App\Http\ViewComposers\ProfileComposer'
);
// Using Closure based composers...
View::composer('dashboard', function ($view) {
//
});
}
/**
* Register the service provider.
*
* #return void
*/
public function register()
{
//
}
}
From the root of your application open Config/app.php and look for the Providers section in the file and copy and past this 'App\Providers\ComposerServiceProvider', to the array.
By doing this, we have created the Composer Service Provider. When you run your application with the view Profile like so http://yourdomain/something/profile, the service provider ComposerServiceProvider is called and the class App\Http\ViewComposers\ProfileComposer is instantiated calling the method Composer due to the code below inside the boot method or function.
// Using class based composers...
View::composer(
'profile', 'App\Http\ViewComposers\ProfileComposer'
);
If you refresh your application you will get an error because the class App\Http\ViewComposers\ProfileComposer does not exist yet. Now lets create it.
Go to the directory path app/Http
Create the directory called ViewComposers
Create the file ProfileComposer.php.
class ProfileComposer
{
/**
* The user repository implementation.
*
* #var UserRepository
*/
protected $users;
/**
* Create a new profile composer.
*
* #param UserRepository $users
* #return void
*/
public function __construct(UserRepository $users)
{
// Dependencies automatically resolved by service container...
$this->users = $users;
}
/**
* Bind data to the view.
*
* #param View $view
* #return void
*/
public function compose(View $view)
{
$view->with('count', $this->users->count());
}
}
Now go to your view or in this case Profile.blade.php and add
{{ $count }}
and that will show the count of users on the profile page.
To show the count on all pages change
// Using class based composers...
View::composer(
'profile', 'App\Http\ViewComposers\ProfileComposer'
);
To
// Using class based composers...
View::composer(
'*', 'App\Http\ViewComposers\ProfileComposer'
);
1) In (app\Providers\AppServiceProvider.php)
// in boot function
view()->composer('*', function ($view) {
$data = User::messages();
$view->with('var_messages',$data);
});
2) in Your User Model
public static function messages(){ // this is just example
$my_id = auth()->user()->id;
$data= Message::whereTo($my_id)->whereIs_read('0')->get();
return $data; // return is required
}
3) in Your View
{{ $var_messages }}
I think that the best way is with View Composers. If someone came here and want to find how can do it with View Composers way, read my answer => How to share a variable across all views?
Laravel 5.6 method: https://laravel.com/docs/5.6/views#passing-data-to-views
Example, with sharing a model collection to all views (AppServiceProvider.php):
use Illuminate\Support\Facades\View;
use App\Product;
public function boot()
{
$products = Product::all();
View::share('products', $products);
}
The documentation is here https://laravel.com/docs/5.4/views#view-composers but i will break it down
1.Look for the directory Providers in your root directory and create the for ComposerServiceProvider.php with content
Inside your config folder you can create a php file name it for example "variable.php" with content below:
<?php
return [
'versionNumber' => '122231',
];
Now inside all the views you can use it like
config('variable.versionNumber')
I created ViewServiceProvider for passing data for multiple views, in Laravel 8
Creating app/Provides/ViewServiceProvider.php file.
class ViewServiceProvider extends ServiceProvider
{
public function register()
{
//
}
public function boot()
{
//for user views(resources/views/user/*)
View::composer(['user.*'], function ($view) {
$f_user = Auth::user();
$f_platform = 'user';
$view->with(compact( 'f_user', 'f_platform'));
});
// for admin views(resources/views/admin/*)
View::composer('admin.*', function ($view) {
$f_admin = Auth::guard('admin')->user();
$f_platform = 'admin';
$view->with(compact( 'f_admin', 'f_platform'));
});
//for all views(resources/views/*)
View::composer('*', function ($view) {
$f_something = [];
$view->with(compact('f_something'));
});
}
}
Register ViewServiceProvider in config/app.php
'providers' => [
...
App\Providers\ViewServiceProvider::class,
],
Using in blades
{{ $f_user }}
{{ $f_platform }}
{{ $f_something }}
{{ $f_admin }}
{{ $f_platform }}
{{ $f_something }}
for example you can return list of all tables in database to the all views of Controller
like this :
public function __construct()
{
$tables = DB::select('SHOW TABLES'); // returns an array of stdObjects
view()->share('tables', $tables);
}
In Laravel 5 and above versions , you can edit boot function in
AppServiceProvider.php to access variable in all views
public function boot()
{
\View::composer('*', function($view){
$view->with('key', 'value');
});
}
"Key" represents the name of the variable which you want to set, so that you can use it later in any .blade.php file and "value" represents the value represented by the variable... For Example :
//setting user role to be accessed by all blade.php files
public function boot(){
//
View::composer('*', function($view){
view->with('role', Auth::user()->infouser->role);
});
}
If are you using Laravel 8 you can do this like that,
class Controller extends BaseController{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
public function __construct(){
$categories = Category::where('show_menu', '=', 1)->where('status', '=', 'approved')->get();
view()->share('categories', $categories);
}}

Laravel : Calling functions defined in base_controller from view

In using the laravel framework, how can I call a function defined in base_controller, in a view. For exacmple:
class Base_Controller extends Controller {
public static function format_something()
{
return something;
}
}
How can i call format_something() in a view file?
Usually the error I get looks something like this:
Method [link_to_action] is not defined on the View class.
Probably a silly question, but thanks in advance!
Edit
Okay! First the correct place to do something like this is in the libraries folder.
Second, problem is that your class cannot have underscores.
So in application/libraries I made file AppHelper.php with class
class AppHelper {
public static function format_something()
{
return something;
}
}
And can call it like:
$formated = AppHelper::format_something;
Thanks for the help and the good forum find Boofus McGoofus.
For me is working:
Create directory "helpers" or whatever and file:
// app/helpers/AppHelper.php
class AppHelper {
public static function format_something()
{
return something;
}
}
Add path to composer.json
// composer.json
"autoload": {
"classmap": [
"app/helpers" // <-------- add this line
]
},
Run: (reload the autoload)
composer dump-autoload
Now you can call:
$formated = AppHelper::format_something();
This answer was written for Laravel 3. For Laravel 4 and after, Lajdák Marek's answer using Composer's autoloader is better.
Functions like format_something() don't belong in the controller. The controller should just be about collecting data from various sources and passing it to the view. It's job is mostly just routing.
I've created a folder called "helpers" in the application folder for all my little helpery functions. To make sure all my controllers, views, and models have access to them, I've included the following in my start.php file:
foreach(glob(path('app').'helpers/*.php') as $filename) {
include $filename;
}
I suspect that there's a better way to do that, but so far it has worked for me.
You can inspire yourself from Laravel framework itself.
I will take your example of a formatter and refer to url helper in Laravel Framework.
Start by creating your own helpers.php file:
<?php
if (! function_exists('format_that')) {
/**
* Generate something
*
* #param string $text
* #return string
*/
function format_that($text)
{
return app('formatter')->format_that($text);
}
}
And add it to your composer.json file:
"autoload": {
"files": [
"app/helpers/helpers.php"
]
}
Run this command to recreate the autoload php file:
$ composer dumpautoload
Create your service provider app/Providers/FormatterServiceProvider.php:
<?php
namespace Illuminate\Routing;
use Illuminate\Support\ServiceProvider;
use App\Helpers\FormatGenerator;
class FormatterServiceProvider extends ServiceProvider
{
/**
* Register the service provider.
*
* #return void
*/
public function register()
{
$this->app['formatter'] = $this->app->share(function ($app) {
return new FormatGenerator($app['request']);
});
}
}
Register your service provider. Laravel framework invokes register method but you only need to add it to your app config file config/app.php:
'providers' => [
/*
* Application Service Providers...
*/
App\Providers\AppServiceProvider::class,
// other providers...
App\Providers\FormatterServiceProvider::class,
]
Finally, create your actual generator class app/Helpers/FormatGenerator.php
<?php
namespace App\Helpers;
use Illuminate\Http\Request;
class FormatGenerator
{
protected $request;
/**
* Create a new URL Generator instance.
*
* #param \Illuminate\Routing\RouteCollection $routes
* #param \Illuminate\Http\Request $request
* #return void
*/
public function __construct(Request $request)
{
$this->request = $request;
}
public function format_that($text){
if ($request->path() == "home"){
return mb_strtoupper($text);
}
else{
return $text;
}
}
}
You can optionally create a Facade app/Facade/Formatter.php, to be able to do Formatter::format_that($text):
<?php
namespace App\Facades;
use Illuminate\Support\Facades\Facade;
/**
* #see \App\Helpers\FormatGenerator
*/
class Formatter extends Facade
{
protected static function getFacadeAccessor() { return 'formatter'; }
}
You could ask yourself:
Why the facade? You can reuse the component somewhere else by simply calling Formatter::format_that($text) instead of app('formatter')->format_that($text). Sugar syntax really.
Why the Service provider? Dependence injections. If you need to use Request or want to build a complex object, the Service provider will take care of that for you and make it available in your $app object.

Categories