0

Here are the sources I wrote.

app\Providers\AppServiceProvider.php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Auth;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        View::share('user_id', Auth::user()->user_id);
    }
}

The following error occurs:

"Trying to get property 'user_id' of non-object"

When I used Auth::user()->user_id elsewhere, it was displayed correctly. But not here. What is the reason?

Udhav Sarvaiya
  • 9,380
  • 13
  • 53
  • 64
b1ix.net
  • 43
  • 7

2 Answers2

1

Does your users table have column named "user_id" or you mean users table "id" column? if you mean users table id column update your code to below.

namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Auth;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        View::share('user_id', Auth::user()->id);
    }
}
  • 'user_id' is my newly created column. Furthermore, If I use `Auth::user()->id`, I will get an error of "Trying to get property 'id' of non-object". – b1ix.net Feb 20 '19 at 05:51
  • Check if you are getting the Auth object try this code add "use Auth" before the class begins and inside boot() write dd(Auth::User()); check if this is returned. – Prashant Prajapati Feb 20 '19 at 05:54
  • I tried `dd(Auth::User ());`. The result is "null". However, some model pages output correctly. – b1ix.net Feb 20 '19 at 06:03
0

I found the reason through the link below.

Laravel - How to get current user in AppServiceProvider

I modified the source as below and it worked.

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Auth;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        view()->composer('*', function ($view)
        {
            View::share('user_id', Auth::user()->user_id);
        }
    }
}
b1ix.net
  • 43
  • 7