Reputation: 161
I'm working on my application using Laravel 7. I have used View Composer in my AppServiceProvider to get the count for a number of items in my database table. I have used where clause to get count for a specific logged in user. The problem is that I'm not sure how I can get the ID of currently logged in User and use in my AppServiceProvider. I have tried doing it but I'm getting Undefined variable: userId
error. Please help. Thanks.
AppServiceProvider:
<?php
namespace App\Providers;
use App\Models\Project;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Auth;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
$userId = Auth::id();
View::composer('client_panel.layouts.menu', function ($view) {
$view->with('newprojects', Project::where([
['status','=','1'],
['created_by','=', $userId]
])->count());
});
}
}
Upvotes: 0
Views: 256
Reputation: 15319
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());
});
Upvotes: 1