access auth for boot method to use variable in master blade - laravel

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);
});
}

Related

I got error getting current url by its name in AppServiceProvider [duplicate]

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());
});
}
}

Laravel Global Variable to specific views

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

Laravel - forgetParameter

My project is multi language, so in most route I add parameter "locale". But latter I do not need to pass "locale" parameter to my controllers. I try to remove this parameter using forgetParameter() method but when I use this method then I have error "Route not bound".
So what I'm doing wrong.
How to remove "locale" from all routes?
Laravel 5.8
My route file.
Route::group(['prefix' => '{locale}','where' => ['locale' => '[a-zA-Z]{2}']], function() {
Auth::routes([app()->getLocale()]);
Route::get('/', 'HomeController#index')->name('mainPage');
Route::get('/user/{id}','UserController#showUser')->name('getUserProfile')->forgetParameter('locale');
Route::get('/user/{id}/edit','UserController#editUser')->name('editUserProfile')
->middleware('can:editUser,App\User,id')->forgetParameter('locale');
Route::patch('/user/{id}/edit','UserController#updateUser')->name('updateUserProfile')
->middleware('can:updateUser,App\User,id')->forgetParameter('locale');
});
It's not duplicate with this question - Laravel 5.4: How to DO NOT use route parameter in controller
Solution in that question doesn't work in my case. And my question is why "forgotParamter()" throw an error?
Other question is, why I can't use this construction in middleware:
$request->route()->forgetParameter('locale')
I have following error:
Call to a member function is() on null
Thank you.
Try to forget the parameter in an inline middleware in the controller's constructor. Actually, I would use a base controller: 1, get the route value; 2, set to a protected property, so inherited controllers can access to the value; 3, forget the parameter.
<?php
// Localized/Controller.php
namespace App\Http\Controllers\Localized;
use App\Http\Controllers\Controller as ControllerBase;
use Illuminate\Http\Request;
class Controller extends ControllerBase
{
protected string $currentLocale;
public function __construct()
{
$this->middleware(function ($request, $next) {
// If you need to access this later on inherited controllers
$this->currentLocale = $request->route('locale') ?? 'en';
// Other operations, like setting the locale or check if lang is available, etc
$request->route()->forgetParameter('locale');
return $next($request);
});
}
}
<?php
// Localized/UserController.php
namespace App\Http\Controllers\Localized;
use Illuminate\Http\Request;
// Extends the our base controller instead of App\Http\Controllers\Controller
class UserController extends Controller
{
public function show(Request $request)
{
// No need of string $locale arg
dd($this->currentLocale);
}
}

Laravel sharing data with all views

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 }}

Laravel | Auth::user()->id isn't working in AppServiceProvider

I can get the Auth ID when i put it in any controller with
Auth::user()->id
But when i put it in AppServiceProvider.php , it returns `Trying to get property 'id' of non-object
i don't understand why ?
Eddit : I tried this but still not working
public function boot()
{
view()->composer('*', function ($view)
{
if (Auth::check())
{
$id=Auth::user()->id;
$idd=Person::where('user_id','=',$id)->get('photo');
$view->with('idd', $idd );
$view->with('id', $id );
}
});
}
Error :
Argument 1 passed to Illuminate\Database\Grammar::columnize() must be of the type array, string given, called in
To get the currently authenticated user's ID, use
Auth::id();
Another case may be that there is not a current user, in which case Auth::user() is returning NULL. Wrap the code in a
if (Auth::check())
{
// Do stuff
}
to make sure there is a user logged in.
view()->composer('*', function($view)
{$view->with('user',auth()->user());
});
it's work for me
<?php
namespace Fitness\Providers;
use Illuminate\Http\Request;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot(Request $request)
{
view()->share('user', $request->user());
}
}

Resources