Many to Many Relationship Join Query between Two Table in Laravel 5.1

Ad

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:

enter image description here

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:

Ad

Answer

Ad

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
}
Ad
source: stackoverflow.com
Ad