Validation Strategies & Route Group
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 namedrules
define all your validation rules and used this as a dependency injection inside thestore
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');
}