Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel relationship not working: getConnectionName() Error

I have two tables users and user_details. I have linked users table as

public function userDetails()
{
    return $this->hasOne('App\Repositories\Models\UserDetails', 'id', 'user_id');
}

and linked user_details table as

public function user()
{
    return $this->belongsTo('App\Repository\Models\User');
}

While from UserController for accessing users data with details, if I try to access the data

return $this->user->with('userDetails')->get();

I get this type of error

FatalErrorException in HasRelationships.php line 488: Call to undefined method

App\Repositories\Models\UserDetails::getConnectionName()

Is there anything wrong?

like image 833
Tijan Manandhar Avatar asked May 29 '17 18:05

Tijan Manandhar


2 Answers

Make sure UserDetails class extends Model class:

use Illuminate\Database\Eloquent\Model;

class UserDetails extends Model
like image 50
Alexey Mezenin Avatar answered Nov 04 '22 06:11

Alexey Mezenin


You can also clean up your code like this. Having neat code will make your code more valuable and it will be easier for other developers to understand or you to remember when you get back to your code later on.

use Illuminate\Database\Eloquent\Model;
use App\Repository\Models\User;
use App\Repository\Models\UserDetails;

public function user()
{
    return $this->belongsTo('User');
}
public function userDetails()
{
    return $this->hasOne('UserDetails', 'id', 'user_id');
}
like image 1
Willie Mwewa Avatar answered Nov 04 '22 06:11

Willie Mwewa