Vichit
Vichit

Reputation: 339

Laravel 5.4 How to responses JSON with Relationship?

I want to response JSON with Laravel that I have CategoryModel belongTo SongModel.

This is my CategoryModel

class CategoryModel extends Model
{
    protected $table = 'categories';
    protected $fillable = [
        'id',
        'name',
    ];

    public function song()
    {
        return $this->hasMany(SongModel::class);
    }
}

And this is my SongModel

class SongModel extends Model
{
    protected $table = 'songs';
    protected $fillable = [
        'id',
        'name',
        'url',
        'categories_id',
        'singers_id',
        'types_id',
    ];

    public function category()
    {
        return $this->belongsTo(CategoryModel::class);
    }
}

I want to response JSON with the relationship. I wrote:

class SongController extends Controller
{
    public function index(SongModel $songModel)
    {
        $song = $songModel->category()->get();
        return response()->json(["DATA" => $song], 201);
    }
}

Upvotes: 0

Views: 2260

Answers (3)

adwairi
adwairi

Reputation: 191

OR, you can use with('song')

lass SongController extends Controller
{
    public function index(SongModel $songModel)
    {
        $song = $songModel::with('song')->get();
        return response()->json(["DATA" => $song], 201);
    }
}

Upvotes: 0

ImPerat0R_
ImPerat0R_

Reputation: 663

Try this. return response()->json(["DATA" => $songModel->load('category')->toArray()], 201);

Upvotes: 1

Rwd
Rwd

Reputation: 35180

To do this you will just need to load the relationship before you return the response:

public function index(SongModel $songModel)
{
    $songModel->load('category');

    return response()->json(["DATA" => $songModel], 201);
}

https://laravel.com/docs/5.4/eloquent-relationships#lazy-eager-loading

Hope this helps!

Upvotes: 3

Related Questions