Laravel 5.7 validation works still not - laravel

I have already asked question about Laravel 5.7 validation, however it still does not work quite right. the validation is not executed at all when sending the content.
public function store(Request $request)
{
$data=$request->all();
$validator = Validator::make($data, [
'first_name' => 'alpha|min:2|max:30',
]);
}
Thanks in advance

if your are not using form validation then maybe it will be helpful for you.
I add validator example in your code, you can try it
maybe your problem will resolve
public function update(Request $request, Player $player)
{
//example validation
$validator = Validator::make($request->all(), [
'id' => 'required|integer', //put your fields
'text' => 'required|string' //put your fields
]);
if ($validator->fails()){
return "Invalid Data";
}
if(Auth::check()){
$playerUpdate = Player::where('id', $player->id)
->update([
'first_name' => $request->input('fist_name'),
'last_name' => $request->input('last_name')
]);
if($playerUpdate){
return redirect()->route('players.show', ['player'=> $player->id])
->with('success' , 'player foo');
}
}
return back()->withInput()->with('errors', 'Foo error');
}

I don't see your validation code at all.
there are two ways for implementing the validation in laravel
Form Request Validation
validation in controller methods
Please Add one, and try again

Related

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;
}

return redirect() is not working after a failed validation

I have a form where users can edit a branch's info, once the user submits that form, the update() method checks for the validity of the submitted data such as the description must be unique to every subscriber. While the validation WORKS, it doesn't redirect to the exact url/page that I want if the validation fails. It stays in the same edit form.
here's the code of my update() method:
public function update(Request $request, $id)
{
$description = $request->input('description');
$message = $request->input('message');
$subscriber_id = auth()->user()->subscriber_id;
$messages = [
'description.unique' => 'Branch already exists!',
];
$this->validate($request, [
'description' => Rule::unique('branches')->where(function ($query) use($subscriber_id) {
return $query->where('subscriber_id', $subscriber_id);
})
], $messages);
Branch::where('id', $id)->update([
'description' => $description,
'message' => $message,
]);
return redirect('branches')->with('success', 'Branch info successfully updated!');
}
Note: the url of the edit form is /branch/edit/{id} while the page I want to redirect after submission is /branches.
Is my validation wrong? Did I miss something?
Thanks! :)
According to the laravel docs you can redirect to a different route by using the Validator facade
public function update(Request $request, $id)
{
$description = $request->input('description');
$message = $request->input('message');
$subscriber_id = auth()->user()->subscriber_id;
$messages = [
'description.unique' => 'Branch already exists!',
];
$validator = Validator::make($request->all(), [
'description' => Rule::unique('branches')->where(function ($query) use($subscriber_id) {
return $query->where('subscriber_id', $subscriber_id);
})
],
$messages);
if ($validator->fails()) {
return redirect('/branches')
->withErrors($validator)
->withInput();
}
Branch::where('id', $id)->update([
'description' => $description,
'message' => $message,
]);
return redirect('branches')->with('success', 'Branch info successfully updated!');
}
Make sure you use the Validator facade at the beginning of your controller file use Validator;

Laravel Functions & their usage

The following code is to add a task to the ToDo list.
What does the Laravel Function ->withInput() & ->withErrors($validator) mean?
Does the withError() has anything to do with common.errors? If so how?
Route::post('/task', function (Request $request) {
$validator = Validator::make($request->all(), ['name' => 'required|max:255',]);
if ($validator->fails()) {
return redirect('/')
->withInput()
->withErrors($validator);
}
$task = new Task;
$task->name = $request->name;
$task->save();
return redirect('/');
});
withInput() meant for flashing your input to your session,so you can use it in the views like after validation fails you can display in the input box what you entered in the form before you submit.So you don't have to enter again.
For details check the documentation https://laravel.com/docs/5.6/requests#old-input
withError() is the method to flash the error messages to the session and you can display those errors in your view.
Check the documentation https://laravel.com/docs/5.6/validation#manually-creating-validators
These two functions is used when you manually create validations
You can also validate the form without these functions using
$request->validate([
'title' => 'required|unique:posts|max:255',
'name' => 'required',
'description' => 'required',
]);

Laravel issue with create()

I've just started some tutorial about Laravel and I got some trouble with this code:
public function store(Request $request )
{
$product = $this->validate(request(), [
'name' => 'required',
'price' => 'required|numeric'
]);
Product::create($product);
return back()->with('success', 'Product has been added');
}
Argument 1 passed to Illuminate\Database\Eloquent\Builder::create()
must be of the type array, null given, called in
C:\~\laravel\framework\src\Illuminate\Database\Eloquent\Model.php on
line 1374 and defined
I have no idea what I did wrong, I'm following this tutorial step by step
You are passing null into create()method because you are not getting request object here try this way
public function store(Request $request )
{
$this->validate($request, [
'name' => 'required',
'price' => 'required|numeric'
]);
Product::create($request->all());
return back()->with('success', 'Product has been added');
}
Alternative
The way I recommend you to Laravel 5.4 is like this
public function store(Request $request )
{
$validator = Validator::make( $request->all(), [
'name' => 'required',
'price' => 'required|numeric'
] );
if ( $validator->fails() ) {
//error handling
}
Product::create($product);
return back()->with('success', 'Product has been added');
}
For Laravel 5.5
As mentioned in chat you are looking for updating Laravel into 5.5 for Laravel 5.5 which is a stable release, I have found a good article here which I read couple of months ago, they have described laravel validation in a decent way it will help you to understand more about it.

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

Resources