Ad

Eloquent Is Setting A Value To Null

- 1 answer

i'm having an error with Eloquent (and Many to Many relationship). This is my code:

$user = new Users;
$rs = $user
    ->company()
    ->where('company_role.users_id', $request->session()->get('usrid'))
    ->where('code', $request->company)
    ->first();

The query that Eloquent perform is this one:

select `companies`.*, `company_role`.`users_id` as `pivot_users_id`, `company_role`.`companies_id` as `pivot_companies_id`, `company_role`.`role_name` as `pivot_role_name` from `companies` inner join `company_role` on `companies`.`id` = `company_role`.`companies_id` where `company_role`.`users_id` is null and `company_role`.`users_id` = 1 and `code` = 12345678901 limit 1)"

How is this possible? Do you guys have any idea?

This is my Users model:

class Users extends Model
{
    //table associated with model
    protected $table = 'users';
    protected $primaryKey = 'id';

    public function company(){
        return $this->belongsToMany('App\Companies','company_role')->withPivot('role_name');
    }
}
Ad

Answer

First, define the variables

$user_id = $request->session()->get('usrid');
$user = User::find($user_id);

Then, you need to find the user and the companies they are attached, and an individual company with the search params

$companies = $user->company()->get();

$company = $user->company()->where('code', $request->company)->first();
Ad
source: stackoverflow.com
Ad