I try to get user id in my app service provider, but I get an error show that ErrorException: Trying to get property of non-object, any idea how on how to get user id?
AppServiceProvider:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Project;
use Log;
use Auth;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
$userid = Auth::user()->id;
Log::info('userid :', [$userid]);
$project = Project::where('user_id',Auth::user()->id)->count();
}
}
Error:
local.ERROR: ErrorException: Trying to get property of non-object in C:\wamp64\www\test\app\Providers\AppServiceProvider.php:20 Stack trace: #0 C:\wamp64\www\test\app\Providers\AppServiceProvider.php(20): Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(8, 'Trying to get p...', 'C:\\wamp64\\www\\f...', 20, Array) #1 [internal function]: App\Providers\AppServiceProvider->boot() #2 C:\wamp64\www\test\vendor\laravel\framework\src\Illuminate\Container\Container.php(507): call_user_func_array(Array, Array) #3 C:\wamp64\www\test\vendor\laravel\framework\src\Illuminate\Foundation\Application.php(734): Illuminate\Container\Container->call(Array) #4 C:\wamp64\www\test\vendor\laravel\framework\src\Illuminate\Foundation\Application.php(717): Illuminate\Foundation\Application->bootProvider(Object(App\Providers\AppServiceProvider)) #5 [internal function]: Illuminate\Foundation\Application->Illuminate\Foundation\{closure}(Object(App\Providers\AppServiceProvider), 19) #6 C:\wamp64\www\test\vendor\laravel\framework\src\Illuminate\Foundation\Application.php(718): array_walk(Array, Object(Closure)) #7 C:\wamp64\www\test\vendor\laravel\framework\src\Illuminate\Foundation\Bootstrap\BootProviders.php(17): Illuminate\Foundation\Application->boot() #8 C:\wamp64\www\test\vendor\laravel\framework\src\Illuminate\Foundation\Application.php(203): Illuminate\Foundation\Bootstrap\BootProviders->bootstrap(Object(Illuminate\Foundation\Application)) #9 C:\wamp64\www\test\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(222): Illuminate\Foundation\Application->bootstrapWith(Array) #10 C:\wamp64\www\test\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(117): Illuminate\Foundation\Http\Kernel->bootstrap() #11 C:\wamp64\www\test\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(87): Illuminate\Foundation\Http\Kernel->sendRequestThroughRouter(Object(Illuminate\Http\Request)) #12 C:\wamp64
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.