I would like assistance with calling a global variable on Laravel app for specific pages or routes.
This is my current code which works on login
App\Providers\AppServiceProvider
public function boot()
{
view()->composer(['auth.login'], function ($view) {
$view->with('settings', AppSetting::where('id',1)->first());
});
}
This is the route for the login page
Route::get('/', function () {
return view('auth.login');
});
[Edit 1]
On the login page , I used this code bellow to get the app version
{{$settings->app_version}}
After digging a little I think a good solution might be caching your AppSetting Model.
Write the given code in App\Providers\RouteServiceProvider
<?php
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Route;
class RouteServiceProvider extends ServiceProvider
{
/**
* Define your route model bindings, pattern filters, etc.
*
* #return void
*/
public function boot()
{
parent::boot();
App::before(function($request) {
App::singleton('settings', function(){
return AppSetting::where('id',1)->first();
});
// If you use this line of code then it'll be available in any view
// as $settings but you may also use app('settings') as well
View::share('settings', app('settings'));
});
}
}
App::singleton will call once AppSetting::where('id',1)->first() and after one call your settings will be cached.
And you can use {{$settings->app_version}} in your view.
Reference: stackoverflow.com/a/25190686/7047493
Related
I have a company parameter set in every route in my application. I am trying to send the variable for that company to each view for easy access.
In my AppServiceProvider.php I tried two things:
$company = App::make('request')->route()->getParameter('company');
view()->share('company', $company);
and also:
$company = Route::getCurrentRoute()->getParameter('company');
view()->share('company', $company);
But with both of them I get the error:
Call to a member function getParameter() on a non-object
How would I go about getting the parameter variable?
Edit:
I am doing it in the boot() function
Answer:
All I did was do the following in my register() function in AppServiceProvider:
view()->composer('*', function ($view) {
// all views will have access to current route
$view->with('company', \Route::getCurrentRoute()->getParameter('company'));
});
Current route is not yet known in AppServiceProvider as the application is still being bootstrapped here. If you want to access route parameters, you could use a view composer - see more details here https://laravel.com/docs/5.1/views#view-composers.
A quick example:
class AppServiceProvider extends ServiceProvider {
public function register()
{
view()->composer('*', function ($view) {
// all views will have access to current rout
$view->with('current_route', \Route::getCurrentRoute());
});
}
}
I want to get only API route names. How can I get all my route names inside of my api.php ?
I'm trying the code below but it lists all the routes of my app.
Route::getRoutes();
I'm waiting for your help
One way to determine is by checking the prefix:
$apiRoutes = collect();
$apiRoutesNames = [];
foreach (\Route::getRoutes() as $route) {
if ($route->action['prefix'] !== 'api') {
continue;
}
$apiRoutes->push($route);
$apiRoutesNames[] = $route->action['as'];
}
$apiRoutesNames = array_filter($apiRoutesNames);
This will work if you did not change the prefix in app/Providers/RouteServiceProvider.php
I had similar issue and clean Laravel 9.
There are few ways to do that, you may get all contents of the api.php, or directly get all information from your RouteServiceProvider.php.
I changed my RouteServiceProvider.php
class RouteServiceProvider extends ServiceProvider
{
/**
* The path to the "home" route for your application.
*
* This is used by Laravel authentication to redirect users after login.
*
* #var string
*/
public const HOME = '/dashboard';
public const API_PREFIX = '/api'; // I added this line
and changed boot method to this:
/**
* Define your route model bindings, pattern filters, etc.
*
* #return void
*/
public function boot()
{
$this->configureRateLimiting();
$this->routes(function () {
Route::prefix(self::API_PREFIX) // to make it dynamic
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
});
}
After that this code should give you all the api routes:
use Illuminate\Support\Facades\Route;
collect(Route::getRoutes())->filter(function ($route){
return $route->action['prefix'] === RouteServiceProvider::API_PREFIX;
});
Or you can use Str::startsWith
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Str;
collect(Route::getRoutes())->filter(function ($route){
return Str::startsWith($route->action['prefix'], RouteServiceProvider::API_PREFIX);
});
You can get all the information from the routes.
I need the ID of the user who is logged in to get a photo in the profile table, here I am trying to use View but only in the index function that gets $profile, I want all files in the view to have $profile
public function index(){
$profil = Profil_user::where('user_id',$auth)->first();
View::share('profil', $profil);
return view('user.index');
}
I have also tried AppServiceProvider but I get an error in the form of a null value if I don't log in, is there a solution to my problem?
public function boot(){
$auth = Auth::user();
dd($auth);
}
exist several way to pass a variable to all views. I explain some ways.
1. use middleware for all routes that you need to pass variable to those:
create middleware (I named it RootMiddleware)
php artisan make:middleware RootMiddleware
go to app/Http/Middleware/RootMiddleware.php and do following example code:
public function handle($request, Closure $next) {
if(auth()->check()) {
$authUser = auth()->user();
$profil = Profil_user::where('user_id',$authUser->id)->first();
view()->share([
'profil', $profil
]);
}
return $next($request);
}
then must register this middleware in app/Http/Kernel.php and put this line 'root' => RootMiddleware::class, to protected $routeMiddleware array.
then use this middleware of routes or routes group, for example:
Route::group(['middleware' => 'root'], function (){
// your routes that need to $profil, of course it can be used for all routers(because in handle function in RootMiddleware you set if
});
or set for single root:
Route::get('/profile', 'ProfileController#profile')->name('profile')->middleware('RootMiddleware');
2. other way that you pass variable to all views with view composer
go to app/Http and create Composers folder and inside it create ProfileComposer.php, inside ProfileComposer.php like this:
<?php
namespace App\Http\View\Composers;
use Illuminate\View\View;
class ProfileComposer
{
public function __construct()
{
}
public function compose(View $view)
{
$profil = Profil_user::where('user_id', auth()->id)->first();
$view->with([
'profil' => $profil
]);
}
}
now it's time create your service provider class, I named it ComposerServiceProvider
write this command in terminal : php artisan make:provider ComposerServiceProvider
after get Provider created successfully. message go to config/app.php and register your provider with put this \App\Providers\ComposerServiceProvider::class to providers array.
now go to app/Providers/ComposerServiceProvider.php and do like following:
namespace App\Providers;
use App\Http\View\Composers\ProfileComposer;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
class ComposerServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* #return void
*/
public function boot()
{
View::composer(
'*' , ProfileComposer::class // is better in your case use write your views that want to send $profil variable to those
);
/* for certain some view */
//View::composer(
// ['profile', 'dashboard'] , ProfileComposer::class
//);
/* for single view */
//View::composer(
// 'app.user.profile' , ProfileComposer::class
//);
}
/**
* Register the application services.
*
* #return void
*/
public function register()
{
}
}
3. is possible that without create a service provider share your variable in AppServiceProvider, go to app/Provider/AppServiceProvider.php and do as follows:
// Using class based composers...
View::composer(
'profile', 'App\Http\View\Composers\ProfileComposer'
);
// Using Closure based composers...
View::composer('dashboard', function ($view) {
//
});
I hope be useful
you can use this
view()->composer('*', function($view)
{
if (Auth::check()) {
$view->with('currentUser', Auth::user());
}else {
$view->with('currentUser', null);
}
});
I'm trying to run a user-related query to fetch data to appear in the top bar of my site on every view.
I've created a new BaseController according to the first answer here:
How to pass data to all views in Laravel 5?
and that's working for a simple test (just sharing a typed-out variable), but when I try and use Auth::user()->id in the __construct method of BaseController (which in my other controllers always returns the ID of the currently logged in user), I get Trying to get property 'id' of non-object.
I've tried adding use App\User at the top of BaseController (even though it isn't usually needed) and also tried adding in the bits for Spatie laravel-permission plugin, but neither has any effect.
I tried dd on Auth::user() and just get 'null'. My feeling is that the user details maybe haven't been loaded at this stage, but BaseController extends Controller same as MyWorkingController extends Controller so I'm not sure why Auth::user()->id doesn't work here when it does normally?
Create a Base Controller which has all the information that you want to share too all controllers/pages/views and let your others controllers extend it.
open file AppServiceProvider.php from folder Providers and write below code in boot function
view()->composer('*', function ($view)
{
$view->with('cartItem', $cart );
});
And now go to your view page and write :
{{ $cartItem }}
You cannot access Auth in constructors because middleware has not been run yet. You can use either View composer or give try this way though i haven't tested.
class BaseController extends Controller {
protected $userId;
public function __construct() {
$this->middleware(function ($request, $next) {
$this->userId= Auth::user()->id;
return $next($request);
});
}
}
Write this in AppServiceProvider.php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;
use DB;
use Auth;
use App\Cart;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Schema::defaultStringLength(191);
view()->composer('*', function ($view)
{
view()->composer('*', function($view)
{
if (Auth::check()) {
$cart = Cart::where('user_id', Auth::user()->user_id)->count();
$view->with('cartItem', $cart );
}else {
$view->with('cartItem', 0);
}
});
});
}
}
In you view simply write
{{ $cartItem }}
For anyone interested, I just encountered the same problem and I've solved it with ServiceProvider:
Define your custom ServiceProvider with the command
php artisan make:provider CustomServiceProvider
Add a reference to your service provider in the config\app.php file, specifically in the providers array, adding this item to it:
\App\Providers\CustomServiceProvider::class,
Declare the variables you want to share in your provider's boot() method and share them by using the view()->share method:
public function boot()
{
$shared_variable = "Hello";
view()->share('shared_variable', $shared_variable);
}
You can now reference your variable in your blade files with the standard notation:
{{ $shared_variable }}
When I am trying to access Auth::user()->id;. its give me
Trying to get property 'id' of non-object
i am trying to access it in boot method for App\Providers
namespace App\Providers;
class AppServiceProvider extends ServiceProvider {
public function boot()
{
Schema::defaultStringLength(191);
$value = Auth::user()->id;
view()->composer('layouts.member', function ($view) use ($value) {
$view->with('value', $value);
});
}
}
I am going to make builder-bulder for query to use variable into master layouts blade.
You can't use Auth facade in the AppServiceProvider as the application is not fully booted yet.
Also, you will get the same error if there is no authenticated user. So it's better to wrap it in an optional method to avoid this error. In this case the value will be null.
However, you can use it inside the closure if you want that's what you want.
public function boot()
{
Schema::defaultStringLength(191);
view()->composer('layouts.member', function ($view) {
$value = optional(Auth::user())->id;
$view->with('value', $value);
});
}