skip to Main Content

Visit Model

        id
        user_id
        visit_date
        public function user()
        {
            return $this->belongsTo(USER::class,'user_id','user_id')->withTrashed();
        }
User Model
user_id
branch_id
name
  public function branch()
    {
        return $this->belongsTo(BRANCH::class,'branch_id','branch_id')->withTrashed();
    }

Branch Model

branch_id
branch_desc

I want to display branch_desc when getting list of Visit.
Currently Im showing only branch_id from User Model

4

Answers


  1. Chosen as BEST ANSWER

    If figured it out.

    Use this in getting list of your model in Controller.
    This is how to query with multiple relationship

    $visit= VISIT::with('USER.BRANCH')->orderBy('user_id','desc');
    

  2. You need to make one to Many relation from visit to user table and user to branch table

    ex. of relationship code:

    //From Visit to User model
    $this->belongsTo(User::class, 'user_id')
    
    //From User to Branch Model
    $this-belongsTo(Branch::clas, 'branch_id')
    

    This will allow you to eager load the relationships in you controller like this

    Visit::with(['user.branch'])
    //Now you will get all visits with neseted users and branch 
    

    I will recommend you to take a look at laravel relationships docs for a better understanding
    Laravel Relationships with eager loading

    Login or Signup to reply.
  3. For 2 layers (or more) relationships, I recommend you install this package from Staudenmeir https://github.com/staudenmeir/eloquent-has-many-deep

    Inside your Visit model, you can add the relationship like this:

    public function branches() {
      $query-> hasManyThrough(Branch::class, User::class);
    }
    

    And for more information , check LaravelDaily tutorial related to this package https://youtu.be/wgdWokrm3Mw

    Login or Signup to reply.
  4. Your question isn’t clear really! However from what I understand from your question you should also have a Branch model and migration.

    So, from visit table you will fetch the users by the relation with user in your visit model.

    public function user()
    {
        return $this->belongsTo(User::class, 'id', 'user_id');
    }
    

    Then when you can fetch your user branches from your User model by your users relation with Branch.

    public function branch()
    {
        return $this->hasMany(Branch::class, 'user_id', 'id');
    }
    

    So, you will fetch data like this:

    $visit->user->branch->description
    

    You can replace description with any column_name_that_wish_to_fetch.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search