Call controller method after validation in Lumen - laravel

Here is a code from Lumen official documentaion
$router->post('/user', function (Request $request) {
$this->validate($request, [
'name' => 'required',
'email' => 'required|email|unique:users'
]);
// Store User...
});
But how I can call controller method after validation ? Docs says nothing about that, please suggest.

In this case ur not passing a controller as parameter to the route, your passing a closure so technically that's your logic (if you want to use controller check code below)
but i assume this is what you should do
$router->post('/user','MyController#myMethod');
Then in your controller
public function myMethod(Request $request){
$this->validate($request, [
'name' => 'required',
'email' => 'required|email|unique:users'
]);
// You do whatever floats your boat here
}

Related

I have a problem with laravel validation logic when im trying to update my data

Hello guys im beginner in laravel and i need some help.I have a problem with my validation.When i store data in my bootstrap modal everyting is fine but when i press edit button and want to update, the same validation logic applies like when i create.When I want to update, if i don't change the name it won't update because it must be unique.
This is my Department Controller
public function store(Request $request)
{
$this->validate($request,[
'name'=>"required|unique:departments|max:255"
]);
$departmentId = $request->department_id;
Department::updateOrCreate(
['id' => $departmentId],
['name' => $request->name, 'description' => $request->description]
);
return response()->json(['success'=>'Department saved successfully.']);
}
As previously mentioned it would be ideal to have this be 2 different methods, but if you want this in one method you can achieve that. You will need to check if that department id is being passed or not to see if this is an update or create, then adjust the rule based on this. You can try something like this:
public function store(Request $request)
{
$unique = \Illuminate\Validation\Rule::unique('deparments');
if ($request->has('deparment_id')) {
$unique->ignore($request->department_id);
}
$this->validate($request, [
'name' => [
'required', $unique, 'max:255',
],
]);
$departmentId = $request->department_id;
Department::updateOrCreate(
['id' => $departmentId],
['name' => $request->name, 'description' => $request->description]
);
return response()->json(['success'=>'Department saved successfully.']);
}
This assumes the deparment_id is only passed for updates.
you can do this :-
$this->validate($request,[
'name' => 'required|unique:departments|max:255,'. $request->department_id,
]);

Laravel form request validation on store and update use same validation

I create laravel form validation request and have unique rules on that validation.
I want use it on store and update method without create new form request validation again.
but the problem is when on store the id doesnt exist and the validate is passed
and when on update i failed the pass the validating because the id is exist on storage
i want to ignore the id on unique rules but use same form validate request
what is best practice to check on form validate request class if this action from store or update method to ignore unique id ?
Ok.. i can do it like #porloscerros Ψ suggest
public function rules()
{
$rules = [
'name' => 'required|string|unique:products|max:255',
];
if (in_array($this->method(), ['PUT', 'PATCH'])) {
$product = $this->route()->parameter('product');
$rules['name'] = [
'required',
'string',
'max:255',
Rule::unique('loan_products')->ignore($product),
];
}
return $rules;
}
Try this, it worked for me.
Laravel unique: third param can exclude the id for example, of the record, like this:
public function rules()
{
return [
'name' => 'required|string|max:255|unique:products,'.$this->id,
];
}
Why are you checking the id when store or update in FormRequest? You don't need this. The id comes to your controller's method like as parameter. Or laravel will create the model using DI in the your controller's method public function update(User $user) and then you can use $user like an instance of User model. You may check the id in web.php or api.php:
https://laravel.com/docs/7.x/routing#parameters-regular-expression-constraints
And I suggest you not to use one FormRequest for two methods. This is bad practice
im using this
$validated = $request->validated();
use this method:
public function createAccount(RegisterRequest $request)
{
$attr = $request->validated();
instead of something like this:
public function createAccount(Request $request)
{
$attr = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|unique:users,email',
'password' => 'required|string|min:6|confirmed'
]);
use php artisan make:request RegisterRequest
public function rules()
{
return [
'name' => 'required|string|max:255',
'email' => 'required|string|email|unique:users,email',
'password' => 'required|string|min:6|confirmed'
];
}
public function rules()
{
if (request()->isMethod('post')) {
$rules = [
'image' => 'required|image|mimes:jpeg,jpg,png|max:2000',
'name' => 'required|unique:categories'
];
} elseif (request()->isMethod('PUT')) {
$rules = [
'name' => 'required|unique:categories,name'
];
}
return $rules;
}

Laravel 6 Backpack 4.0: How to get the current page ID in FormRequest class or can I get by without using FormRequest classes?

In my UpdateUserRequest class I have a validation rule that requires using the page ID to exclude the current record from validation. Question is, how can I get the current page ID?
public function rules()
{
return [
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users_admin,email,'. $page_id,
];
}
I know how to do it without the FormRequest class basically by just using the update(Request $request, $id) method in the controller.
I have tried doing this basic way which is by writing a update(Request $request, $id) method in the controller and performing the validations in there. The validation works as expected but then there's another problem of the page wasn't redirecting properly in the Backpack admin after saving.
I actually prefer this basic approach (using store() and update() methods in the controller) than having to have separate FormRequest classes for create and update validations.
Thank you.
We can get the id with the below simple way , i have tried it and it works for me.
public function rules()
{
$page_id = $this->get('id') ?? request()->route('id');
return [
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users_admin,email,'. $page_id,
];
}
Referenced from the below mentioned url
https://github.com/Laravel-Backpack/PermissionManager/blob/master/src/app/Http/Requests/UserUpdateCrudRequest.php
It's better to use the unique method of the Illuminate\Validation\Rule class:
public function rules(): array
{
return [
'name' => [
'required',
Rule::unique('post')->ignore(request()->route('id'))
],
];
}
Detailed description in laravel documentation:
https://laravel.com/docs/9.x/validation#rule-unique

Custom Validation Laravel multiple attributes 5.5

In my form I have 2 attributes that need to be unique, I am trying to use Laravels Validator to do this but am very stuck..
Even if i add a return false/true to the function, there are no errors generated and the controller continues on. Am I missing something (not according to their docs :| )
$validator = Validator::make($request->all(), [
'organisationid' => 'required',
'membershipcode' => 'required'
]);
$validator->sometimes('membershipcode', 'required', function($input) {
return false;
});
In the store method in your controller, you can add validation like this:
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|unique',
'description' => 'required',
]);
$movie = Model::create($request->all());
return redirect('view')->with('message', 'Added successfully');
}
The available validation rules are here: https://laravel.com/docs/5.5/validation#available-validation-rules

Simply validate email in laravel without creating validator

How can I simply validate an email in laravel, without creating a validator?
Validator::email($email)
does not work
By laravel ref
We can do like this Validator::make(['email' => $email], [ 'email' => 'email'])
OR
By using laravel helper we can do like this
validator(['email' => $email], ['email' => 'required|email']);
OR
Edit: We can further simplefy this by using macro
Add this in Service provider
$this
->app
->make(Validator::class)
->macro('email', function ($email) {
return Validator::make(['email' => $email], [ 'email' => 'email'])
});
And now we can use like this
Validator::email($email)
Note: Not test this just throwing some idea we can do this way.
The BaseController uses ValidatesRequests trait so in the controller you can do...
public function store(Request $request)
{
$this->validate($request, [
'email' => 'email',
]);
//
}
How about using PHP filter_var?
https://www.php.net/manual/en/filter.filters.validate.php
filter_var($email, FILTER_VALIDATE_EMAIL)

Resources