Search code examples
laravellaravel-5laravel-validationlaravel-request

Laravel: how to use validator for single elements?


I'm trying to make validation of $id and $offer_id inside my function:

public function getMessagesForOffer($id, $offer_id)
{

    $validator = Validator::make($request->all(), [
        'id' => 'required|numeric',
        'offer_id' => 'required|numeric',
    ]);
    if ($validator->fails()) {
        return response([
            'status' => 'error',
            'error' => 'invalid.credentials',
            'message' => 'Invalid credentials'
        ], 400);
    }    
 }

This is throwing an error: "message": "Undefined variable: request",

And I see that it's incorrect coded, how can I correct it to work with single elements when there is no request inside my function?


Solution

  • $request->all() would just return array, so you can also use array here, so instead of $request->all() you can use:

    ['id' => $id, 'offer_id' => $offer_id]
    

    or shorter:

    compact('id', 'offer_id')