Search code examples
phplaravel-5.7

Call to a member function phone() on null


I am trying to store phone record using one to one relationship.

public function store(Request $request) {

    $user= auth()->user(); 

    $phone= new Phone();

    $phone->cellno= request('cellno');

    $user->phone()->save($phone); 
    return redirect('/phones');
}

screenshot


Solution

  • The recommended way to retrieve the authenticated user is indicated in the documentation.

    The line:

    $user = auth()->user(); 
    

    Should be:

    $user = Auth::user();
    

    And don't forget to use the class Auth:

    use Illuminate\Support\Facades\Auth;
    

    Explanation:

    The auth() or user() methods are not available in your current context, so that's why $user will be null if none of them were found.

    Edit:

    The authentication will also return null if none user is authenticated, you must follow the documentation provided below for implementing it. Then, you can secure your Routes.

    Basically you have two options:

    a) Add the middleware in the route specification:

    Route::resource('phones' , 'PhoneController')->middleware('auth');
    

    b) Add the middleware into the construct of the class (recommended for controllers)

    public function __construct()
    {
        $this->middleware('auth');
    }
    

    After that, if there is not authenticated user the access will be restricted.