Laravel - How to get current user in AppServiceProvider
Laravel session is initialized in a middleware so you can't access the session from a Service Provider, because they execute before the middleware in the request lifecycle
You should use a middleware to share your varibles from the session
However, If for some other reason you want to do it in a service provider, you can do it using a view composer with a callback, like this:
public function boot()
{
//compose all the views....
view()->composer('*', function ($view)
{
$cart = Cart::where('user_id', Auth::user()->id);
//...with this variable
$view->with('cart', $cart );
});
}
The callback will be executed only when the view is actually being composed, so middlewares will be already executed and session will be available
Laravel | Auth::user()-id isn't working in AppServiceProvider
To get the currently authenticated user's ID, useAuth::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.
How can I get the ID of logged in user and use it in my AppServiceProvider file in Laravel 7?
The error is because of , you cant call outside variable directly inside callback's. So you have to pass using use
params. function ($view)($userId){
But I don't think auth user
will available in service provider's So
call inside View composer.
View::composer('client_panel.layouts.menu', function ($view) {
$view->with('newprojects', Project::where([
['status','=','1'],
['created_by','=',Auth::user()->id]
])->count());
});
Laravel - How to get user id in app service provider
Use View::composer('*',)
to use Auth in all view .
use Illuminate\Support\Facades\View;
.........
public function boot()
{
View::composer('*', function($view)
{
if (Auth::check()){
$project = Project::where('user_id',Auth::id() )->count();
}
});
You can understand it as after authentication before view render you need to check between these not before.
Access user in AppServiceProvider?
The reason why the Auth
methods do not work in a direct context in the AppSeviceProvider
, is that the Auth system is not loaded yet. In the defined closure, the Auth system will be available, as it always loaded before this closure is executed. Hence, the problem is in the way the view composer is used.
The composer
method only accepts an array (or a string) of view identifiers and an *
. Therefore, the following options are available:
Define multiple views
View::composer(['about', 'contact'], function ($view)
{
if (Auth::check())
{
View::share('key', 'value');
}
}
Define one view, and make this the main parent view for all the relevant pages
You could, for example, define a main.blade.php
and extend this view with all relevant views.
@extends('main')
And just share the main
view:
View::composer('main', function ($view)
{
if (Auth::check())
{
View::share('key', 'value');
}
}
There are other options available, for example filters or a parent controller. Excellent answer here.
Use Auth in AppServiceProvider
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
Laravel AppServiceProvider Auth::guard('admin')-check() not working
you need view composer for this.
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Auth;
use DB;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
view()->composer('*', function ($view)
{
if (Auth::guard('admin')->check()) {
}
});
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}
If you want to pass data in views.
view()->composer('*', function ($view)
{
if (Auth::guard('admin')->check()) {
$admin = DB::table('admins')->first(); // for example
$view->with(compact('admin'));
}
});
Auth data is not accessible in AppServiceProvider Laravel 5.5
Why?
It is because, when the boot
method of a service provider is being called, the user is not yet authenticated.
Solution:
I guess you are trying to use View Composers
From the documentation:
So, what if we need to register a view composer within our service
provider? This should be done within the boot method. This method is
called after all other service providers have been registered, meaning
you have access to all other services that have been registered by the
framework:
So you can use the following:
public function boot(Guard $auth) {
view()->composer('*', function($view) use ($auth) {
$user = $auth->user();
// other application logic...
$view->with('currentUser', $user);
});
}
use authentication in a AppServiceProvider in laravel
You can use Auth::check()
to check whether the user is authenticated or not like this:
public function boot()
{
view()->composer('app.shop.2.layouts.master', function($view) {
if (Auth::check()){
$data = \Auth::user()->cart()->get()->first()->products();
$view->with('data', $data);
}
});
}
Related Topics
Check If Laravel Model Got Saved or Query Got Executed
Understanding PHP Curl_Multi_Exec
Get All Defined Classes of a Parent Class in PHP
Multi-Byte Safe Wordwrap() Function for Utf-8
Do PHP Pdo Prepared Statements Need to Be Escaped
Replacing Variables in a String
MySQL Stored Procedure VS. Complex Query
How to Make 5 Random Numbers with Sum of 100
PHP Get Previous Array Element Knowing Current Array Key
Best Way to Autoload Classes in PHP
PHP Soap Client That Understands Multi-Part Messages