Many To Many Relationship Join Query Between Two Table In Laravel 5.1
First User
table have four columns: id ,first_name, last_name,password
my Address
Table have four colmnns id , company_name,email , phone
Common Address_user
Table:
My User Model Look Like This http://pastebin.com/ntuvJ8Lj and my Address Model Look Like This
use Illuminate\Database\Eloquent\Model;
class Address extends Model
{
protected $fillable = [
'created_by',
'company_name',
'phone',
'email', 'address'
];
public function users()
{
return $this->belongsToMany('App\Models\User');
}
public function getAddressListAttribute()
{
return $this->users->lists('id');
}
}
now I need the all of address which login user is involved or connected
1:
Answer
in User.php
Add your relation with 'address' model:
public function addresses() {
return $this->belongsToMany( Address::class, 'address_id', 'user_id' )->withTimestamps();
}
You wrote right relation in your Address.php
with users
therefore, I'm not going to retype it here.
and please note that you don't need to write address_id
and user_id
because simply eloquent will predict it if you are following the convention, which you do!
But I can tell that you are not following the convention of naming your tables, if you want Eloquent to predict and relation between your model and your table in DB then you have to make the name of your model the singular of your table name, or vice versa, table: users
model: User
.
The Gist:
$user = auth()->user(); // get logged in user
$addresses = $user->addresses()->get(); // get this user addresses. or use $user->addresses only
// now you may loop through it and have each of your addresses.
foreach($addresses as $address){
var_dump($address->company_name); // or perhabs ->email
}
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS - Conditionally Load a Different Page
- → Make a Laravel collection into angular array (octobercms)
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?
- → Validating fileupload(image Dimensions) in Backend Octobercms
- → OctoberCMS Fileupload completely destroys my backend
- → How do I call the value from another backed page form and use it on a component in OctoberCms