API Route, Middleware and FormRequest

Posted 1 month ago by clodoaldobragato

Dear friends,

I have the following need:

  1. Create an API to add some data to the database
  2. Create a FormRequest to validate this data
  3. Create a Middleware that modifies some of these data before persiting them.

Well, I followed these steps, but my middleware does not fire when I call the API.

I registered it in App \ Http \ Kernel.php, and added it to the route in the API route file.

Can someone help me?

To complement this information the Laravel Version is 5.8.10

Controller:

use App\Http\Requests\Customer\CustomerRequest;
class CustomerController extends Controller
{

  public function add(CustomerRequest $request){

    $fullname = $request->input('firstname').' '.$request->input('lastname');
    $customer = Customer::firstOrCreate(["name"=>$fullname,]);
    $customer->user()->firstOrCreate($request->all());

    return response()->json($customer->with(["user"]),200);

  }
}

api.php

Route::prefix('customer')->group(function(){
    Route::post('/','Api\Customer\[email protected]')->middleware('customer');
});

CustomerRequest.php

namespace App\Http\Requests\Customer;

use Illuminate\Foundation\Http\FormRequest;

class CustomerRequest 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 [
          'email'=>'required|email|unique:users,email',
          'firstname'=>'required|string|min:5|max:20',
          'lastname'=>'required|string|min:1|max:100',
          'hash'=>'required|string|min:6|max:255',
        ];
    }

    public function messages(){
      return [
        'email.required'=>__('e-Mail is required'),
        'email.email'=>__('e-Mail must be a valid address'),
        'email.unique'=>__('This e-Mail is already registered'),
        'firstname.required'=>__('Firstname is required'),
        'firstname.string'=>__('Firstname must be a string'),
        'firstname.min'=>__('Fisrtname must have a minimal of 5 characters'),
        'firstname.max'=>__('Fisrtname must have a maximal of 20 characters'),
        'lastname.required'=>__('Lastname is required'),
        'lastname.string'=>__('Lastname must be a string'),
        'lastname.min'=>__('Lastname must have a minimal of 1 characters'),
        'lastname.max'=>__('Lastname must have a maximal of 100 characters'),
        'hash.required'=>__('Password is required'),
        'hash.string'=>__('Password must be a string'),
        'hash.min'=>__('Password must have a minimal of 6 characters'),
        'hash.max'=>__('Password must have a maximal of 255 characters'),
      ];
    }
}

CustomerMiddleware.php

namespace App\Http\Middleware\Customer;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Symfony\Component\HttpFoundation\ParameterBag;
use App\Http\Requests\Customer\CustomerRequest;

class CustomerMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(CustomerRequest $request, Closure $next)
    {

      if($request->isJson()){
        $this->modify($request->json());
      }else{
        $this->modify($request->request);
      }

      return $next($request);
    }

    private function modify(ParameterBag $bag){
      $bag->replace($this->modifyData($bag->all()));
    }

    private function modifyData(array $data){
      return collect($data)->map(function($value,$key){
        switch ($key) {
          case 'firstname':
            return ucwords(strtolower($value));
            break;
          case 'lastname':
            return ucwords(strtolower($value));
            break;
          case 'hash':
            return Hash::make($value);
            break;
        }
      })->all();
    }
}

Kernel.php

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
        'user' => \App\Http\Middleware\Authentication\UserMiddleware::class,
        'customer' => \App\Http\Middleware\Customer\CustomerMiddleware::class,
    ];

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.