When calling another method of controller where injected custom request class. it is showing error Call to a member function validated() on null

47 views Asked by At

I am using Laravel 10. I want to call store method of Admin controller from AdminV1Controller

class AdminV1Controller extends Controller
{
    public function store(AdminV1Request  $request): \Illuminate\Http\JsonResponse
    {
        try {
            $validatedData = $request->validated();
            return (new AdminController)->store(new StoreEventRequest($validatedData));
        } catch (\Exception $e) {
            Log::error('Failed to store event: ' , ["error=>"=>$e->getMessage()]);
            return response()->json(['message' => 'Failed to store event', 'error' => $e->getMessage()], 500);
        }
    }
}

But I am getting error (Call to a member function validated() on null) on AdminController when reach on this line $validatedData = $request->validated();

class AdminController extends Controller
{
   public function store(StoreEventRequest $request)
    {
        try {
            $validatedData = $request->validated();
            $event = Event::createEvent($validatedData);
            return response()
                    ->json(['message' => 'Event created successfully', 'data' => new EventResource($event)], 201);
        } catch (\Exception $e) {
            Log::error('Failed to create event: ' , ["error" => $e->getMessage()] );
            return response()->json(['message' => 'Failed to create event', 'error' => $e->getMessage()], 500);
        }
    }
}

This the request of AdminV1Request where define validation rules


<?php

namespace App\Http\Requests\Admin;

use App\Enums\ValidationEnum;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;

class AdminV1Request 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
     */
    public function rules(): array
    {
        return [
            'name' => 'required|string|max:255',
            'description' => 'required|string',
            'date' => 'required|date|date_format:Y-m-d',
            'location' => 'required|string|max:255',
        ];
    }

    /**
     * Handle a failed validation attempt.
     *
     * @param Validator $validator
     * @return void
     * @throws HttpResponseException
     */
    public function failedValidation(Validator $validator): void
    {
        throw new HttpResponseException(response()->json([
            'success'   => false,
            'message'   => 'Validation errors',
            'data'      => $validator->errors()
        ]));
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function messages(): array
    {
        return [
            'name.required' => ValidationEnum::REQUIRED_MESSAGE->value,
            'name.string' => ValidationEnum::STRING_MESSAGE->value,
            'name.max' => 'The :attribute may not be greater than :max characters.',
            'description.required' => ValidationEnum::REQUIRED_MESSAGE->value,
            'description.string' => ValidationEnum::STRING_MESSAGE->value,
            'date.required' => ValidationEnum::REQUIRED_MESSAGE->value,
            'date.date' => 'The :attribute must be a valid date.',
            'date.date_format' => 'The :attribute must be a YYYY-MM-DD format.',
            'location.required' => ValidationEnum::REQUIRED_MESSAGE->value,
            'location.string' => ValidationEnum::STRING_MESSAGE->value,
            'location.max' => 'The :attribute may not be greater than :max characters.',
        ];
    }
}

This the request of AdminRequest where define validation rules


<?php

namespace App\Http\Requests\Admin;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;


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

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => 'nullable|string|max:255',
            'description' => 'nullable|string',
            'date' => 'nullable|date|date_format:Y-m-d',
            'location' => 'nullable|string|max:255',
        ];
    }

    /**
     * Handle a failed validation attempt.
     *
     * @param Validator $validator
     * @return void
     * @throws HttpResponseException
     */
    public function failedValidation(Validator $validator)
    {
        throw new HttpResponseException(response()->json([
            'success'   => false,
            'message'   => 'Validation errors',
            'data'      => $validator->errors()
        ]));
    }

    /**
     * Get custom error messages for validator errors.
     *
     * @return array
     */
    public function messages()
    {
        return [
        
            'name.string' => 'The :attribute must be a string.',
            'name.max' => 'The :attribute may not be greater than :max characters.',
            'description.string' => 'The :attribute must be a string.',
            'date.date' => 'The :attribute must be a valid date.',
            'date.date_format' => 'The :attribute must be a YYYY-MM-DD format.',
            'location.string' => 'The :attribute must be a string.',
            'location.max' => 'The :attribute may not be greater than :max characters.',
        ];
    }
}

api.php

<?php

Route::controller(Admin::class)
       ->prefix('admin')
       ->middleware(['auth:api'])
       ->group(function () {
            Route::post('/event',  'store');
            Route::put('/event/{id}', 'update')->where('id', '[0-9]+');
            Route::delete('/event/{id}', 'destroy')->where('id', '[0-9]+');
            Route::get('/events',  'index');
});

Route::controller(AdminV1::class)
    ->prefix('admin/v1')
    ->middleware(['auth:api'])
    ->group(function () {
        Route::post('/event',  'store');
        Route::put('/event/{id}', 'update')->where('id', '[0-9]+');
        Route::delete('/event/{id}', 'destroy')->where('id', '[0-9]+');
        Route::get('/events',  'index');
    });

I tried to solve the issue, but I am unable to understand why it's not working. I want a validator in the AdminController->store method to prevent unwanted data. Could you please suggest what I am missing? Thank you.

0

There are 0 answers