noobie-php
noobie-php

Reputation: 7233

laravel belongsTo on User Model not working

Following are my relations in laravel , I am unable to access company using User's Object, but i am getting null when i try to access it, please see my code below to get the picture

following are my models

<?php

namespace App\Models;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Zizaco\Entrust\Traits\EntrustUserTrait;
use Session;
use Illuminate\Support\Facades\DB;

class User extends Authenticatable
{
    use Notifiable;
    use EntrustUserTrait;

    protected $table = 'tbl_users';
    protected $primaryKey = 'id';
    protected $guarded = ['id'];
    const API = 'api';
    const WEB = 'web';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'last_login', 'Address', 'Age', 'DateOfBirth', 'created_by', 'deleted_by'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    protected $casts = [
        'is_admin' => 'boolean',
    ];

    public function isAdmin()
    {
        return $this->is_admin;
    }

    static function GetUserNamebyID($id)
    {
        $name = User::select("name")->where(["id" => $id])->pluck('name');
        if (isset($name[0])) {
            return $name[0];
        } else {
            return '';
        }
    }



    public function loginlogout()
    {
        $this->hasMany("App\Models\LoginLogoutLogs", 'userID');
    }

    public function company()
    {
        $this->hasMany("App\Models\Company", "company_id");
    }
}

And following is my companies Model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use DB;
use App\Models\CarePlanData;
use Session;

class Company extends Model
{
    protected $table = 'companies';
    protected $primaryKey = 'id';
    protected $guarded = ['id'];

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'phone_no', 'address', 'password', 'description', 'city', 'company_logo', 'country', 'email'
    ];

    static public function fetchAllActiveCompanies()
    {

        return DB::table("companies")->where(['is_active' => 1])->pluck('name', 'id');
    }

// change company to hasmany

    public function users()
    {
        return $this->hasmany('App\Models\User');
    }

}

and this is how i am trying to access the Company , but i am getting null.

public function fetchCompany(){
 $User = User::find($user->id);
        dd($User->company());
}

Upvotes: 1

Views: 3542

Answers (3)

TechnicalKeera
TechnicalKeera

Reputation: 1043

Your actual question is: You have belongTo Relation between User and Company but when you trying to access the Company via user object, you get null

In your User.php Model put the following function but if you already have then leave it:

public function company()
{
    $this->belongsTo("App\Models\Company", "company_id");
}

Then

Replace this function:

public function fetchCompany(){
 $User = User::find($user->id);
        dd($User->company());
}  

To is one:

public function fetchCompany(){
    $User = User::find($user->id);
    if($User){ 
        dd($User->company()->get());
    }
} 

or to this one:

 public function fetchCompany(){
    $User = User::find($user->id);
    if($User){ 
        dd($User->company);
    }
} 

Upvotes: 1

Dmitry
Dmitry

Reputation: 7246

First of all if a user belongs to 1 company then it should be:

public function company()
{
    $this->belongsTo("App\Models\Company", "company_id");
}

then fetchCompany() should be

public function fetchCompany(){
   $User = User::with('company')->find($user->id);
   dd($User->company);
}

You need to use with to load the relations. You pass the name of the function which defines the relation in your User model to with like this with('function_name').

Upvotes: 1

Yannis Berrouag
Yannis Berrouag

Reputation: 356

actually if your company_id field is on user model, then your relation should be

public function company()
    {
        $this->belongsTo("App\Models\Company", "company_id");
    }

unless a user can have many companies ?

Upvotes: 0

Related Questions