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?
2
Answers
I have found the solution! In the controller I first need to retrieve the record:
}
Check that the
education_type_id
in theEducation
model corresponds to an existingid
in theEducationType
model in your database. May be the foreign key is not set correctly.