Nas Atchia Nas Atchia - 7 months ago 20
PHP Question

Laravel - Many to Many relationship

I have 2 tables, users and pictures. The tables have a many-to-many relationship and I have created a pivot table name user_pictures.

The users table is as follows:

id
firstname
lastname


The pictures table is as follows:

id
filename
url


The user_pictures table contains:

id
user_id
picture_id


When a user adds a picture, the picture filename and url is stored in the pictures table, and in the user_pictures table the picture_id of that picture is stored alongside the user_id of that user.

How can I retrieve all the picture filename and url related to the user that have added them using Eloquent ORM?

Answer
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $table = 'users';
    // Define pictures with a pivot table link
    public function pictures() {
        return $this->belongsToMany('App\Models\UserPicture', 'user_pictures', 'picture_id', 'user_id');
    }
    //add methods
}

class UserPicture extends Model
{
    protected $table = 'user_pictures';
    public function picture() {
        return $this->hasOne('App\Models\Picture', 'id', 'picture_id');
    }

    public function user() {
        return $this->hasOne('App\Models\User', 'id', 'user_id');
    }
    //add methods
}

class Pictures extends Model
{
    protected $table = 'pictures';
    //add methods
}

If you don't want to add timestamps to the tables you must add these 2 methods:

 public function setCreatedAt($value) {
        // to disable created_at
    }

    public function setUpdatedAt($value) {
        // to disable created_at
    }

To fetch pictures from a user do this:

$userPictures = UserPicture::where(array('user_id'=>1)->get();
foreach($userPictures as $userpicture) {
    $picture = $userpicture->picture();
}
Comments