Skip to content

Validation Strategies & Route Group

Compare
Choose a tag to compare
@ahmadhuss ahmadhuss released this 06 Apr 20:27
· 30 commits to master since this release

Here we deal with the validation with 2 methods inside the store function which will be invoked when the user wants to create the new Product.

  • Using default Request $request dependency injection and invoke the validate method.
  public function store(Request $request)
    {
        // If validation fails it will redirect back to same form.
        $request->validate([
            'name' => 'required',
            'price' => 'required|decimal',
        ]);

      Product::create([
            'name' => $request->name,
            'price' => $request->price,
            'category_id' => $request->category_id,
            'description' => $request->description,
            'photo' => ''
        ]);
        return redirect()->route('products.index');
    }
  • Create the Request class with artisan and inside the method of this class named rules define all your validation rules and used this as a dependency injection inside the store function.
php artisan make:request StoreProductRequest
class StoreProductRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'name' => 'required',
            'price' => 'required|decimal',
        ];
    }
}
  public function store(StoreProductRequest $request)
    {
     
        Product::create([
            'name' => $request->name,
            'price' => $request->price,
            'category_id' => $request->category_id,
            'description' => $request->description,
            'photo' => ''
        ]);
        return redirect()->route('products.index');
    }