PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, February 6, 2022

[FIXED] Access Data From Pivot Table On Model

 February 06, 2022     eloquent, laravel, php     No comments   

Issue

I need to get data from a pivot table.

I have 2 models: sites, technologies. These 2 models are related by a pivot table called site_technology, this table has 2 columns called col_a, col_b that I would like to access. Right now I have this:

class Site{
  public function technologies(){
    return $this->hasMany('App\Models\Technology')
  }
}

My question is, how do I link the 2 models, and how do I access the data on that piovt table with eloquent?


Solution

I see this question a lot, the best way I have found to do this is with the following code.

class Site{
  public function technologies(){
    return $this->belongsToMany(Technology::class, 'PIVOT_TABLE')->withPivot('column_a', 'column_b')
  }
}

This will allow you to get the data by doing this.

$data = Site::first()->technologies->first()->pivot->column_b

I hope this helped!



Answered By - dragon-froot
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing