dimanche 6 août 2017

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);

    }
}



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2wyMmsl
via IFTTT

Aucun commentaire:

Enregistrer un commentaire