Laravel API – Get list of users I have favourited and their information

I am building an API in Laravel 5 and want to get list of people I have favourited and their information.

User model

class User extends Model implements AuthenticatableContract, CanResetPasswordContract {

use Authenticatable, CanResetPassword;

/**
 * The database table used by the model.
 *
 * @var string
 */
protected $table = 'users';

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = ['username', 'email', 'password'];

/**
 * The attributes excluded from the model's JSON form.
 *
 * @var array
 */
protected $hidden = [
    'password',    
    'secret_key'
];

public function attribute()
{
    return $this->hasOne('AppUserAttributes', 'user_id', 'id');
}

public function photos()
{
    return $this->hasMany('AppPhotos', 'user_id', 'id');
}

public function favourites()
{
    return $this->hasMany('AppFavourites', 'from', 'id');
}

public function favourited()
{
    return $this->hasMany('AppFavourites', 'to', 'id');
}

Favourites Model

class Favourites extends Model {

   protected $table = 'favourite';

   public function user()
   {
       return $this->belongsTo('AppUser', 'from', 'id');
    }

}

User Attributes Model

class UserAttributes extends Model {

    protected $table = 'user_attributes';

    public function user()
    {
       return $this->belongsTo('User', 'user_id', 'id');
    }
}
  • User table holds information like username, email password etc.
  • Attribute table holds information like height, weight, etc. (this is so that the user’s table doesn’t have 70 columns)
  • Favourite table holds from and to columns. From is my user id and to is the user ID I have fvaourited.

This is what I currently have:

return User::with(['attribute','favourites'])->find($user_id);

What I want to achieve is similar to below:

"favourites": [
    {
        "id": "15",
        "from": "231", // My ID
        "to": "**100**", // ID of user I have favourited (FK)
        "created_date": "2013-04-10 21:35:28",
        "user": [
            "id": "**100**", // USER ID
            "username": "someuser",
            "email": "random@mail.com",
            "email_verified": "1",
            "has_photo": "1",
            "dob": "1952-11-12"
        ],
        "attribute": [
            "id": "105",
            "user_id": "**100**", // USER ID (FK)
            "height": "70",
            "car": "0",
            "pet": "2",
        ]
    }
]

I need my json like above so that when I call the api URL /api/v1/favourites?my_id=231 in my app or site and get all the required information rather than loading it all individually. Unless I am wrong?

If you think this way of doing this is wrong for an app, I would be more than happy to hear your input as this is something new to me so please bare with me 🙂


Source: laravel

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.