Laravel 5.2.26 get form validation data array - validation

I submit the form and have some validation mean email,require,unique email,
when validation have error message then laravel 5.2 return validation return array.

I guess you want to retain the submitted data on error.
Considering a sample
public function postJobs(Request $request) {
$input = $request->all();
$messages = [
'job_title.required' => trans('job.title_required'),
];
$validator = Validator::make($request->all(), [
'job_title' => 'required'
], $messages);
if ($validator->fails()) { // redirect if validation fails, note the ->withErrors($validator)
return redirect()
->route('your.route')
->withErrors($validator)
->withInput();
}
// Do other stuff if no error
}
And, in the view you can handle errors like this:
<div class="<?php if (count($errors) > 0) { echo 'alert alert-danger'; } ?>" >
<ul>
#if (count($errors) > 0)
#foreach ($errors->all() as $error)
<li>{!! $error !!}</li>
#endforeach
#endif
</ul>
</div>
And if you want the input data, you need to redirect with ->withInput(); which can be fetch in view like:
Update
<input name= "job_title" value="{{ Request::old('job_title') }}" />
But, the best thing is to use laravel Form package so they all are handled automatically.

If you just need form data, you can use Request object:
public function store(Request $request)
{
$name = $request->input('firstName');
}
https://laravel.com/docs/5.1/requests#accessing-the-request
Alternatively, you could use $request->get('firstName');

Use old() to get previous value from input. Example:
<input name="firstName" value="{{old('firstName')}}">
See documentation here https://laravel.com/docs/5.1/requests#old-input

Related

Set "custom" withErrors without Request->validation in Laravel

I want to display an error in a form, but it cannot be checked via validation.
Blade
<form action="/githubuser" methode="GET">
<div class="error">{{ $errors->first('CustomeError') }}</div>
<input type="text" name="userName" placeholder="GitHub Username ..." value="John12341234">
#if($errors->has('userName'))
<div class="error">{{ $errors->first('userName') }}</div>
#endif
<input type="submit" value="SUBMIT">
</form>
The Problem is that I start an api call after validation. and if I don't get "GitHubUser" as a response, I want to print an error message in the blade. GitHub user not found.
Controller
public function show(Request $request)
{
$rules = ['userName' => 'required'];
$validator = \Validator::make($request->input(), $rules);
if ($validator->fails()) {
return redirect('/')
->withErrors($validator)
->withInput();
}
$data = $this->gitHubUserService->getUserData($request->input('userName'));
/* User on Github not Found **/
if (! $data) {
// >>> THE LINE BELOW IS MY PROBLEM! <<<
return view('form')->withErrors($validator);
}
// ....
}
At the end of the day I want the line <div class="error">{{ $errors->first('CustomeError') }}</div> to be displayed in the blade.
Is this possible? Thanks in advance!
The original validator is not getting any error, because there are none. So, just add a new error to the errors inside of your if body before returning form view:
if(! $data){
$validator->errors()->add('customError', 'Github User not found!');
return view('form')->withErrors($validator);
}

Flash messages display and sometimes they don't

I'm using a spatie/laravel-flash for displaying some flash messages. It works when I use simple HTML forms, but when I use Vue.js templates, the message doesn't show. (and sometimes they don't) after submitting the form and go to the next request.
main layout
<div class="col-lg-12 mb-2">
#include('layouts.partials.flash_message')
</div>
<section class="py-5">
#yield('content')
</section>
layouts.partials.flash_message
#if(flash()->message)
<div class="{{ flash()->class }} alert-dismissible" role="alert">
<button type="button" class="close close-white" data-dismiss="alert">×</button>
{{ flash()->message }}
</div>
#endif
create.blade.php
#extends('layouts.main_layout')
#section('content')
<create-school> </create-school>
#endsection
Vue.js template store() method
store()
{
axios.post('/master/schools', {
name: this.name,
}.then((response) => {
this.name = ''
}));
}
Laravel store method
<?php
public function store(Request $request)
{
$school = School::create([
'name' => $request->name,
]);
flash('success message', 'alert alert-success');
return back();
}
Since you are using ajax to store your data, you will need to provide the message as a response in that request. So basically the store method on your controller would look like
public function store(Request $request)
{
$school = School::create([
'name' => $request->name,
]);
return response($school, 201);
}
201 is the HTTP code to indicate a resource was created, and the by the RFC you should return the resource in the response.
In your Vue file, the store method would then be
store()
{
axios.post('/master/schools', {
name: this.name,
}.then((response) => {
this.name = ''
// Modify your DOM or alert the user
alert('Resource created')
}));
}
As a recomendation, you should aways validate user input before storing.

laravel pass validation error to custom view

I created a validation but cant show it on view, its important to return search view and don't redirect back user. help me please, thanks all?
Controller :
public function search(Request $request)
{
$msg = Validator::make($request->all(), [
'search' => 'required'
]);
if ($msg->fails()) {
return view('layouts.search')->withErrors($msg->messages());
} else {
return "Thank you!";
}
}
View :
#if($errors->any())
<ul class="alert alert-danger">
#foreach($errors as $error)
<li> {{$error}} </li>
#endforeach
</ul>
#else
You can use $error->first('name_of_error_field') to show error messages.
You can do it like this:
public function search(Request $request)
{
$validator = Validator::make($request->all(), [
'search' => 'required'
]);
if ($validator->fails()) {
return view('layouts.search')->withErrors($validator); // <----- Send the validator here
} else {
return "Thank you!";
}
}
And in view:
#if($errors->any())
<ul class="alert alert-danger">
#foreach($errors as $error)
<li> {{$error->first('name_of_error_field')}} </li>
#endforeach
</ul>
#endif
See more about Laravel Custom Validators
Hope this helps

Validation error in Laravel - $errors array does not get populated after the validation failure

I've ran into a strange issue regarding validations in Laravel 5.2. I reviewed following questions on StackOverflow, but none of them seems to apply to my case:
Laravel validation not showing errors
Laravel Validation not returning error
The thing is, that I am trying to validate a title field, before persisting the Card object into the database. When I submit the form with an empty title field, as expected, It doesn't pass the validations. However, the $errors array doesn't get populated upon failure of the mentioned validations. Can anybody explain where am I going wrong with this code?
/////////////////////// CONTROLLER /////////////////////
public function create(Request $request)
{
$this->validate($request, [
'title' => 'required|min:10'
]);
Card::create($request->all());
return back();
}
///////////////////////// VIEW /////////////////////////
// Show errors, if any. (never gets triggered)
#if(count($errors))
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
#endif
<form method="POST" action="/cards">
{{ csrf_field() }}
<div class="form-group">
// The textarea does not get populated with the 'old' value as well
<textarea class="form-control" name="title">{{ old('title') }}</textarea>
</div>
<div class="form-group">
<button class="btn btn-primary" type="submit">Add Card</button>
</div>
</form>
If you are running Laravel 5.2.27 and up, you no longer need to use the web middleware group. In fact, you shouldn't add it to your routes because it's now automatically applied by default.
If you open up your app/Http/RouteServiceProvider.php file, you will see this bit of code:
protected function mapWebRoutes(Router $router)
{
$router->group([
'namespace' => $this->namespace, 'middleware' => 'web',
], function ($router) {
require app_path('Http/routes.php');
});
}
Source: https://github.com/laravel/laravel/blob/master/app/Providers/RouteServiceProvider.php#L53
As you can see, it's automatically applying the web middleware for you. If you try to apply it again (more than once) in your routes file, you'll run into weird problems like what you are currently facing.
In order to find out the version of Laravel that you are running, run this command: php artisan --version
I guess you have to set the if clause to #if(count($errors) > 0)
In your controller, try adding a $validator->fails() statement, and using ->withErrors() to return any errors to your template.
public function create(Request $request)
{
$validator = Validator::make($request->all(), [
'title' => 'required|min:10'
]);
if ($validator->fails()) {
return back()->withErrors($validator);
}
Card::create($request->all());
return back();
}

Laravel MessageBag errors array is empty in view but with content if I kill script

I am trying to return errors back to my view, this is part of my controller TestcategoryController
$rules =array(
'name' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
//process
if($validator->fails()){
return Redirect::to('testcategory/create')->withErrors($validator);
}
In the view testcategory/create if I try and output the errors like
#if($errors->any())
{{ $errors->first('name') }}
#endif
I get nothing. But if I {{dd($errors)}} I get
object(Illuminate\Support\ViewErrorBag)#91 (1) { ["bags":protected]=> array(1) {
["default"]=> object(Illuminate\Support\MessageBag)#92 (2)
{ ["messages":protected]=> array(1)
{ ["name"]=> array(1) { [0]=> string(27) "The name field is required." } }
["format":protected]=> string(8) ":message" } } }
The only way I am getting the errors is if I kill the script. What am I doing wrong?
Probably another issue would be with $errors not being saved to Session variable $errors and nothing being shown in the view.
Here is an example of the same issue:
http://laravel.io/forum/03-28-2016-errors-variable-empty-after-failed-validation
For me the solution defined in the above link worked.
Solution: Is in app\Http\Kernel.php
Move
\Illuminate\Session\Middleware\StartSession::class, from $middlewareGroups to $middleware
Before
After
If you get nothing in your case, than it means you have overridden your $errors object with something else or with empty object - check your code and data you pass to the views. Your code is perfectly valid and works good - I've tested it locally. Maybe, you passed empty $errors object to your subview, but in other views the correct object is used.
You need to use it like this:
{{ $errors->getBag('default')->first('name') }}
Route::group(['middleware' => ['web']], function() {
Route::get('/home', 'HomeController#index')->name('home');
});
Add middleware, and resolved..
I was having the same problem with Laravel 8.0
The only way I could solve this was by entering the error bags layer by layer until I got to the messages manually:
#if (count($errors->getBags()))
<div class="alert alert-danger">
<ul>
#foreach ($errors->getBags() as $bag)
#foreach ($bag->getMessages() as $messages)
#foreach ($messages as $message)
<li>{{ $message }}</li>
#endforeach
#endforeach
#endforeach
</ul>
</div>
#endif

Resources