Search code examples
phplaravellaravel-10laravel-middlewarelaravel-eloquent-resource

Laravel JsonResource foreign table is empty


I'm a beginner with Laravel and inertia. I use Laravel 10 with Inertia and react.

When I go to the index page, the field "$this->typeEducation->title" is filled, but when I click edit, the field is empty. I then get the error message: "Attempt to read property "title" on null"

The model:

class Education extends Model
{
    use HasFactory;

    protected $fillable = [
        'title',
        'education_type_id',
        'is_active',
        'start_date',
        'end_date',
    ];

    public function typeEducation() {
        return $this->belongsTo(EducationType::class, 'education_type_id', 'id');
    }
}

The resource:

class EducationResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'type' => $this->typeEducation->title,
            'isActive' => $this->is_active,
            'startDate' => $this->start_date,
            'endDate' => $this->end_date,
            'educationTypes' => EducationTypeResource::collection($this->whenLoaded('educationTypes'))
        ];
    }
}

The Controller

class EducationController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(): Response
    {
        return Inertia::render('School/Education/EducationIndex', [
            'education' => EducationResource::collection(Education::all())
        ]);
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Education $education): Response
    {
        $education->load(['typeEducation']);
        return Inertia::render('School/Education/Edit', [
            'education' => new EducationResource($education),
            'educationTypes' => EducationTypeResource::collection(EducationType::all())
        ]);
    }
}

What am I doing wrong?


Solution

  • I have found the solution! In the controller I first need to retrieve the record:

    class EducationController extends Controller {
        public function index(): Response {
            return Inertia::render('School/Education/EducationIndex', [
                'education' => EducationResource::collection(Education::all())
            ]);
        }
    
        public function edit(string $id): Response {
            $education = Education::findOrFail($id);
            $education->load(['typeEducation']);
            return Inertia::render('School/Education/Edit', [
                'education' => new EducationResource($education),
                'educationTypes' => EducationTypeResource::collection(EducationType::all())
            ]);
        }
    }