skip to Main Content

I’m using apiResource using Postman I try to get a specific item ("services"), update and delete by API controller but does not work and returns null values.

Here are the details:

Services model

<?php

namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;

class Services extends Model
{
    use HasFactory;
    protected $fillable= [
        'Service','Added_By'
    ];
}

ServiceController

<?php

namespace AppHttpControllersApi;

use AppHttpControllersController;
use AppModelsServices;
use AppHttpRequestsStoreServicesRequest;
use AppHttpRequestsUpdateServicesRequest;
use AppHttpResourcesServiceResource;

class ServiceController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        dd(ServiceResource::collection((Services::query()->orderBy('id','desc')->paginate(10))));
      return  ServiceResource::collection((Services::query()->orderBy('id','desc')->paginate(10))) ;
    }
    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreServicesRequest $request)
    {
        $data=$request->validated();
        $service=Services::create($data);
        return response(new ServiceResource($service),201);
    }
    /**
     * Display the specified resource.
     */
    public function show(Services $services)
    {
        dump($services);
        return new ServiceResource($services);
    }
    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateServicesRequest $request, Services $services)
    {
        $data=$request->validated();
        $services->update($data);
        return new ServiceResource($services);
    }
    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Services $services)
    {
       $services->delete();
       return response("", 204);

    }
}

UpdateServiceRequest

<?php

namespace AppHttpRequests;

use IlluminateFoundationHttpFormRequest;

class UpdateServicesRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, IlluminateContractsValidationValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        return [
            "Service"=>"required",
            "Added_By"=>"nullable",
        ];
    }
}

API route

<?php

use AppHttpControllersapiapiController;
use AppHttpControllersApiServiceController;
use AppHttpControllersApiUserController;
use AppHttpControllersAuthController;
use IlluminateHttpRequest;
use IlluminateSupportFacadesRoute;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "api" middleware group. Make something great!
|
*/
Route::middleware('auth:sanctum')->group(function(){
    Route::post('/logout',[AuthController::class,'logout']);    
    Route::get('/user', function (Request $request) {
            return $request->user();
        });
       

        Route::apiResource('/users', UserController::class);
        Route::apiResource("/services",ServiceController::class);


});



Route::post('login',[AuthController::class,'login']);
Route::post('register',[AuthController::class,'register']);


<?php

namespace AppHttpResources;

use IlluminateHttpRequest;
use IlluminateHttpResourcesJsonJsonResource;

class ServiceResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        return [
            "id"=>$this->id,
            "Service"=>$this->Service,
            "Added_By"=>$this->Added_By,
            "Date"=>$this->created_at,
            
        ];
    }
}

When I try to get a specific service via Postman by http://127.0.0.1:8000/api/services/1 but gives me:

{
    "id": null,
    "Service": null,
    "Added_By": null,
    "Date": null
}

Same result when trying updating.
Also nothing is deleting when trying.

Notice that for index and store methods is working fine.

2

Answers


  1. public function show(Services $services)
    {
        return new ServiceResource($services);
    }
    
    public function update(UpdateServicesRequest $request, Services $services)
    {
        $data = $request->validated();
        $services->update($data);
        return new ServiceResource($services);
    }
    

    In your routes, ensure you are using the correct parameter for binding:

    Route::apiResource("/services", ServiceController::class);
    
    Login or Signup to reply.
  2. This happens because you named the variable "$services". Laravel is looking to bind to $service (/services/{service}).

    More information here: (https://laravel.com/docs/11.x/controllers#restful-naming-resource-route-parameters)

    Your index and store routes work fine because they don’t require a parameter.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search