Laravel Functions & their usage - laravel

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',
]);

Related

Laravel 5.7 validation works still not

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

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,
]);

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;

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

Laravel/Lumen: validating data for email already exist and general validation

I am writing an API. I was wondering how could I return proper response.
data is not valid (only if email aready exists)
data is not valid (general validation errors)
Here is my code so far:
$data = Input::all();
$validator = Validator::make($request->all(), [
'email' => 'required|email|unique:users,email',
'some_other_field' => 'required'
]);
if ($validator->fails()) {
// NOTE: using a or b, this are my custom methods
a) return $this->existsResponse($data);
b) return $this->badRequestResponse($data);
}
How could I figure out if email already exists?
You should look at the Validator Class. I think the Methods invalid() and valid() should be the right for you. This methods gives you an array of keys back.
http://laravel.com/api/5.0/Illuminate/Validation/Validator.html#method_invalid
Well, you're trying to do two different types of validations, so it would make sense to use two different validators:
$data = $request->all();
// validate email
$validator = Validator::make($data, [
'email' => 'required|email|unique:users,email',
]);
if ($validator->fails()) {
return $this->existsResponse($data);
}
// email valid, so validate other data
$validator = Validator::make($data, [
'some_other_field' => 'required'
]);
if ($validator->fails()) {
return $this->badRequestResponse($data);
}
// if here, all data is valid
I have solved it like this.
public function store(Request $request)
{
$data = Input::all();
// validating data
$validator = Validator::make($request->all(), [
'email' => 'required|email',
'some_other_field' => 'required'
]);
if ($validator->fails()) {
return $this->badRequestResponse($data);
}
// validating if resource exists
$userExists = User::where('email', $request->email)->count();
if($userExists) {
return $this->existsResponse($data);
}
// inserting data
$user = new User();
$user->fill($data);
$user->save();
if($user->save()) {
return $this->createdResponse($data);
}
}

Resources