Can u show us the BookResource ?
Oct 14, 2022
8
Level 1
Laravel apiResource: show, update, delete method not working
I'm figuring this out on why it always give me an empty array while the other controllers give me the result i want.
Booking Model:
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'status_id'
];
/**
* The relationships that should always be loaded.
*
* @var array
*/
protected $with = ['status'];
BookingController (not working):
/**
* Display the specified resource.
*
* @param \App\Models\Booking $booking
* @return \Illuminate\Http\Response
*/
public function show(Booking $booking)
{
return new BookingResource($booking);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Booking $booking
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Booking $booking)
{
$status_id = 1;
$booking->update([
'status_id' => $status_id
]);
return new BookingResource($booking);
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Booking $booking
* @return \Illuminate\Http\Response
*/
public function destroy(Booking $booking)
{
...
}
Other Controller (SizeController) (working)
/**
* Display the specified resource.
*
* @param \App\Models\Size $size
* @return \Illuminate\Http\Response
*/
public function show(Size $size)
{
return new SizeResource($size);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Size $size
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Size $size)
{
$request->validate([
'type' => ['required', 'string', 'unique:sizes,type,'.$size->id],
'abbrv' => ['nullable', 'alpha_num', 'string']
]);
$size->update(['type' => $request->type, 'abbrv' => $abbrv]);
return new SizeResource($size);
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Size $size
* @return \Illuminate\Http\Response
*/
public function destroy(Size $size)
{
...
}
Size Model:
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'abbrv',
'type'
];
Example result I want from BookingController at show method:
{
"data": {
"status_id": 1
}
}
The result I got:
{
"data": []
}
Example result I want from SizeController at show method:
{
"data": {
"type": "test"
"abbrv": "test"
}
}
The result I got:
{
"data": {
"type": "test"
"abbrv": "test"
}
}
Level 1
Ok, I rediscovered the root of the problem. My api route is:
Route::apiResource('/test-booking', BookingController::class);
Where it should be:
Route::apiResource('/booking', BookingController::class);
The endpoint must match with the given controller name.
Please or to participate in this conversation.