0
votes

Hello I have two models User and Car and a pivot table user_car which has two columns user_id and car_id, the combination of the two columns is always unique. Any user can have many cars and one car is assigned to only one user

In the User model I have this

public function cars()
{
    return $this->belongsToMany('App\Car', 'user_car');
}

In the Car model I have this

public function user()
{
    return $this->belongsToMany(
        'App\User', 'user_car', 'car_id', 'user_id'
    );
}


$user->cars

returns all the cars for the user as collection which is fine, but I want

$car->user

returns also collection which is only one user. I do not want collection, I want for example to get the user id like this

$car->user->id
1

1 Answers

0
votes

Please use laravel default naming convention like alphabetically car_user so that you can follow along. Also it's not a many to many relationship as you've stated in your case it's a one to many relationship. A many to many relationship example something like an author can have many books published and a book can have many authors behind it so in a database table it would be like author_id and book_id in a table

Author_Id | book_id |

1 2

1 1

so in your case it would be like

class User {
public function cars()
{
    return $this->hasMany('App\Car');
}
}

make sure you have user_id field in your cars table and in your Car

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

so that you can query it up like

$user = User::first();
$user->car->car_name ; 

or when you start w/ car

// to pluck the specific car
$car = Car::find(3); 
$car->user->full_name  or owner depends upon you