I Create New form request and use this for all CRUD operations
and use $this->getMethod();
to check the different between requests
then I face logical issues
Is all fields that required in store method should be required in update method ?
=> the question here is should the consumer of APIs should sent all keys object to update specific key
If It shouldn't and the keys name sent from APIs is different from the Database table columns name
=> I can't use update($request()->all());
because the key isn't the same as columns name, then I need to loop on all request keys to ignore the key that have null - can be done also by multi-check -
So please what the best practice of that ??
Welcometo Stackoverflow.
There are many methods of validation in laravel,
What I prefer is not to write validation in controller and write it in separate request and use that request object as parameter.
Lets assume we are having user model and and name is required and unique in add and edit method of your controller you can simple use UserRequest object as describe below.
Create request class
php artisan make:request UserRequest
class UserRequeset extends Request
{
/**
* Get the validation rules that apply to the request.
* @return array
*/
public function rules()
{
$id = request('id') ?: 'NULL'; //To identify if request is for add or edit just take autoincremented id parameter form request.
return [
'name' =>'required|unique:users,name,'.$id
];
// you can also customize your validation for different methods as below
switch ($this->method()){
case 'POST':
return [
// validation for post method
];
break;
case 'PUT':
return [
// validation for put method
];
break;
default:
return [];
break;
}
}
public function messages()
{
return [
"name.required" => "User name is required",
"name.unique" => "User name should be unique"
// or you can customize this using language
"name.required" => __("user.required_message"),
"name.unique" => __("user.unique_message")
];
}
}
in UserController
use App\Http\Requests\UserRequest;
Class UserController extends Controller {
public function add(UserRequest $request)
{
//Enter your code just after validation part no need of any validation code here
}
public function update(UserRequest $request)
{
//Enter your update code just after validation part no need of any validation code here
}
}
Hope it's helpful.
Ok the question here if I have name and phone and both is not allow null in database, if the section of PUT, POST in POST (insertion) all is required, and in update user may change name or phone or both so if I should enter required in both POST and PUT for the 2 fields ??
even user want to update one of them, or user should sent the full object if it updated or not
probably yes,
required
should be in both the methodsalso instead of using method checking you can simply follow the first step which will work same for both the cases.