Search code examples
laravellaravel-10

How to get a joined data in laravel from Resources for an api


I watched a tutorial on youtube on how to return datas from database with eloquent. it worked for the basics but i dont know how to join the foreign keys from beasiswas with the primary key in mitras. I tried to import the tables models into the resource file but it says that the "id" column names are the same for both tables. but when i specify which id is which with something like "beasiswas.id" and "mitras.id", it say that it doesnt recognize the "beasiswas". These are my codes.

App\Http\Resources\V1\BeasiswaResource

<?php

namespace App\Http\Resources\V1;
use App\Models\Beasiswa;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class BeasiswaResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        $beas = Beasiswa::join('mitras','beasiswas.id','=','mitras.id')->get();
        
        
        return [
            'idBeasiswa'=>$beas->beasiswas.id,
            'idMitra'=>$beas->id_mitra,
            'deskripsi'=>$beas->deskripsi,
            'angkatanAwal'=>$beas->angkatan_awal,
            'angkatanAkhir'=>$beas->angkatan_akhir,
            'semMin'=>$beas->sem_min,
            'semMax'=>$beas->sem_max,
            'status'=>$beas->status
        ];
    }
}

App\Http\Controllers\Api\V1

<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\Beasiswa;
use App\Http\Controllers\Controller;
use App\Http\Requests\StoreBeasiswaRequest;
use App\Http\Requests\UpdateBeasiswaRequest;
use App\Http\Resources\V1\BeasiswaResource;
use App\Http\Resources\V1\BeasiswaCollection;

class BeasiswaController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        return new BeasiswaCollection(Beasiswa::paginate());
    }
...

Solution

  • To futher explain my comment, do the relationship on model:

    class Beasiswa extends Model
    {
        public function mitra()
        {
            return $this->belongsTo(Mitra::class);
        }
    }
    

    later to the resource you can call that relation:

    class BeasiswaResource extends JsonResource
    {
        public function toArray($request)
        {
            return [
                'idBeasiswa' => $this->id,
                'idMitra' => $this->mitra->id, //make here MitraResource don't know the fields.
                'deskripsi' => $this->deskripsi,
                'angkatanAwal' => $this->angkatan_awal,
                'angkatanAkhir' => $this->angkatan_akhir,
                'semMin' => $this->sem_min,
                'semMax' => $this->sem_max,
                'status' => $this->status,
            ];
        }
    }