Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.5 Trying to get property 'id' of non-object

I'm new on Laravel.I used Laravel version 5.5

If I try to login with postman.I got "Trying to get property 'id' of non-object" error.And error line is

    private $client;

public function __construct(){
    $this->client = Client::find(1);
}

public function login(Request $request){

    $this->validate($request, [
        'username' => 'required',
        'password' => 'required'
    ]);

    return $this->issueToken($request, 'password'); // this line has error

}

issueToken Function

public function issueToken(Request $request, $grantType, $scope = ""){

    $params = [
        'grant_type' => $grantType,
        'client_id' => $this->client->id,
        'client_secret' => $this->client->secret,           
        'scope' => $scope
    ];

    if($grantType !== 'social'){
        $params['username'] = $request->username ?: $request->email;
    }

    $request->request->add($params);

    $proxy = Request::create('oauth/token', 'POST');

    return Route::dispatch($proxy);

}

I got same error on Register.But my user successfully registered with 500 error (Trying to get property 'id' of non-object)

like image 982
more Avatar asked Jan 24 '18 12:01

more


3 Answers

The error is because $this->client is null when find() cannot find the record.

You need to be sure if the record exists or not.

Change:

$this->client = Client::find(1);

To:

$this->client = Client::findOrFail(1);

Documentation:

From Laravel Eloquent docs, this will throw a 404 error if no record with the specified id is found.

like image 101
Sapnesh Naik Avatar answered Nov 15 '22 21:11

Sapnesh Naik


Make sure you have record in database table for User model with id = 1. When you're using User::find(1) Laravel tries to get this record from database, if record is absent this will return null

like image 34
Nimfus Avatar answered Nov 15 '22 19:11

Nimfus


In your issueToken() method-

$client = Client::find(1);
if($client!=null){
     $params = [
       'grant_type' => $grantType,
       'client_id' => $client->id,
       'client_secret' => $client->secret,           
       'scope' => $scope
    ];
}else{
    $params = [
       'grant_type' => $grantType,
       'client_id' => null,
       'client_secret' => null,           
       'scope' => $scope
    ];
}
like image 1
Sohel0415 Avatar answered Nov 15 '22 21:11

Sohel0415