Laravel Lumen API Validation in Service Class

If you need a validation outside of controller such as service container or service class, below example code may help.

Copy traits ProvidesConvenienceMethods from laravel/lumen-framework/src/Routing to your folder as convenient. Eg, App\Services folder.


namespace App\Services\product;

use App\Models\Products\Product;

use App\Services\ProvidesConvenienceMethods;

class ProductCreateService
{
    use ProvidesConvenienceMethods;

    public function store($request)
    {       
        // validate request data
        $product_data = $this->validator($request->all(), [
            'name' => 'required|string|min:1|max:255',
            'sku' => 'required|string|min:1|max:120',
            'qty_available' => 'numeric|required|min:1',

            // validate each array element if array items
            'items.*.sku' => 'required|string|min:1|max:120',
            'items.*.qty_required' => 'numeric|required|min:1',
            'items.*.item_price' => 'required|regex:/^\d+(\.\d{1,2})?$/'
        ]);

According to the documentation: “By default, Lumen’s base controller class uses a ProvidesConvenienceMethods trait which provides a convenient method to validate incoming HTTP request with a variety of powerful validation rules.”

Reference: https://lumen.laravel.com/docs/8.x/validation

Hope this helped someone out there.

By Keenlio, February 18, 2021

What do you think?

Leave a Reply

Your email address will not be published. Required fields are marked *


+ 4 = ten

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>