Vladimir Štus Vladimir Štus - 10 months ago 56
PHP Question

Laravel one to many relationship results

Hello i am trying to create one to many relationship. One user from user table could have many companies, on other side company could have only one user.

my migration for company table is

public function up()
Schema::create('companies', function (Blueprint $table) {

my user model is

* Get the posts for the user.
public function companies()
return $this->hasOne('App\Company','user_id');

my company model is

public function users()
return $this->belongsTo('App\User','id');

i am trying to get all companies for specific user

try with whereHas but no data in relation object

$results = Company::whereHas('users', function ($query) {

Where is my error?

Answer Source

First thing you should change is companies() relation. It has to be hasMany, not hasOne:

public function companies()
    return $this->hasMany('App\Company');

Then get user with all his companies:

$result = User::where('id', $id)->with('companies')->first();

Or, if you want to use Company model like in your example and get only companies:

$result = Company::where('user_id', $id)->get();

Also, you're using id_user in migration. Change it to user_id.