FormRequest page
class UserSaveRequest extends FormRequest{
....
public function rules()
{
return [
'st_email'=>'required|email',
'st_USN'=>'required|max:15',
'st_phone'=>'max:15',
'st_address'=>'string|max:30',
'st_department'=>'string|max:50',
'st_semester'=>'max:4'
];
}
public function message(){
return [
'required' =>'not null',
'string' =>'string',
'st_USN.max' =>'max15',
'st_phone.max' =>'max15',
'st_address.max' =>'max30',
'st_department.max' =>'max50',
'st_semester.max' =>'max4',
'email' =>'email plz'
];
}
}
In the blade.php page, i just add this code.
#if ($errors->any())
<div class="alert alert-danger">
<ul>
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
In the controller part
public function saveStudent(UserSaveRequest $request){
.....
}
I wanna show some error message by my setting, but it always not working.
In addition, if i added the condition of the integer, the error message will always show "max" error. In fact, the size of the input data is not over 4.
'st_semester'=>'max:4|integer'
The st semester may not be greater than 4.
By the way, single rule will be allowed.
'st_semester'=>'max:4' or 'st_semester'=>'integer'
Have anyone know how to solve these problems?
Related
What I'm trying to acheive?
Validate the records available in the csv file that I have uploaded using maatwebsite/excel.
Set custom validation rules:
i.e.
contact_number to be integer and 13 digits
email to be strictly email etc
If all the csv file data is valid then upload in database and show
message.
If certain feild of the table is missing or not according to custom validation rules set above then show those data rows of the csv file in the blade and give user the option to update the feild and upload that data to DB.
What I'm doing?
Using Laravel Excel, I'm importing the data. I am not quite sure how the back end works.
public function import(Request $request)
{
Excel::import(new CustomersImport, $request->file);
return back()->with('success', 'User Imported Successfully.');
}
What Row Validation is showing is that they set the rules inside rules() function inside the import class and create model with table feilds. Tbh I really don't know how csv data is being transferred here. Data is also not uploading in database.
Whwn I enter dd($row) inside the model(array $row) it shows the recod of only first row of the table.
class CustomersImport implements ToModel, WithHeadingRow
{
use Importable;
public function rules(): array
{
return [
'name' => 'required|string',
'email' => 'required|string',
];
}
public function model(array $row)
{
return new Customer([
"name" => $row['name'],
"email" => $row['email'],
"contact" => $row['contact'],
"address" => $row['address'],
"nutritionplan_id" => $row['nutritionplan_id'],
"company_id" => $row['company_id'],
]);
}
}
blade file. I actuality, I want I want to show table with records that are not validated if it have errors. But for now I'm just trying to show error.
#if (count($errors) > 0)
<div class="row">
<div class="col-md-8 col-md-offset-1">
<div class="alert alert-danger alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-ban"></i> Error!</h4>
#foreach($errors->all() as $error)
{{ $error }} <br>
#endforeach
</div>
</div>
</div>
#endif
#if (Session::has('success'))
<div class="row">
<div class="col-md-8 col-md-offset-1">
<div class="alert alert-success alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h5>{!! Session::get('success') !!}</h5>
</div>
</div>
</div>
#endif
What I try to do is to get a message in the session when redirecting back to the page from exception handler class, When I get 'PostTooLargeException' It should back to page with a message.
If statement in Handler class
public function render($request, Exception $exception)
{
//...
if ($exception instanceof PostTooLargeException) {
$test = redirect()->route('clientbank.create')->with('message', 'File too large!'); //Cannot get message
return $test;
//dump($gg);
dump(session('message'));
dd('stop');
}
// this will still show the error if there is any in your code.
return parent::render($request, $exception);
}
}
In dump(session('message')); I can see the message .
In blade page
#elseif(session('message'))
<div class="alert alert-danger alert-dismissible fade show" role="alert">
{{ session('message') }}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
#endif
In controller
public function create()
{
dump(session('message')); <-- getting null !!!
return view('clinetbank.bank.cratebank');
}
What I try to do is use empyt(session('message') I always get an empty session.
Also, I try this questions but not work for me.
I use laravel 5.8
Any ideas, please ?.
I'm trying to access the $errors variable to my view but it returns an error. Please see my code below.
Controller
$validator = Validator::make($request->all(), [...]);
if($request->required == 1){
$validator = Validator::make($request->all(), [...]);
}
if($validator->fails()){
return Redirect::back()->withErrors($validator)->withInput();
}
View
#if($errors->any())
... Some HTML code here
#endif
Error
Call to a member function any() on string
Any idea? This should work, but it is not.
Reference: https://laravel.com/docs/5.5/validation#quick-displaying-the-validation-errors
Laravel version: 5.5
You need to change your line as per below:
From
return Redirect::back()->withErrors($validator)->withInput();
To
return Redirect::back()->withErrors($validator->errors())->withInput();
Then in you blade file you can access it as:
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
I use validation in view like this below
<div class="{{'form-group required'.$errors->first('name',' has-error')}}">
<label>Title</label>
<input type="text" name="name" class="form-control" required>
<div class="text-danger">{{$errors->has('name') ? $errors->first('name') : ''}}</div>
</div>
I need validate and generate error message if same user try to insert existing project_name to the table in Laravel 5.2. My project table like this
user_id project_name
1 abc
2 sdf
3 kju
My project data store controller as follow
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|min:3'
]);
$project = new Project;
$project->project_name = $request->input('name');
$project->user_id = Auth::user()->id;
$project->save();
return redirect()->route('projects.index')->with('info','Your Project has been created successfully');
}
and I have alert.blade.php file as
#if ( session()->has('info'))
<div class="alert alert-info" role-"alert">
{{ session()->get('info') }}
</div>
#endif
#if ( session()->has('warning'))
<div class="alert alert-danger" role-"alert">
{{ session()->get('warning') }}
</div>
#endif
how can I do this?
If your form validation is failed then a 422(Unprocessable) response is returned by laravel. And an $error variable will be available in the response. So you can check if the variable is empty or not, and you can display the errors.
Like Below code. This is from laravel 5.2 documentation.
<!-- /resources/views/post/create.blade.php -->
<h1>Create Post</h1>
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<!-- Create Post Form -->
https://laravel.com/docs/5.2/validation
You could foreach the variable $errors if you want catch the error message,
or if you are asking the validation rule, you could use 'exists:database'
https://laravel.com/docs/5.2/validation#rule-exists
I am trying to Get Validation Errors on index.blade.php having issues:
When I fill both the fields then it goes well if i just put an Echo or Return in getLogin Controller.
When I just fill one field and it works good if i just put and echo or Return but not giving validation errors, with Validation Errors it only shows, "Something went Wrong"
Code for index.blade.php
<section class="mainWrap">
<div class="headingfirst"><img src="{{ URL::asset('css/des.png') }}" width="78"></div>
<div class="sedhead">Hey User!!!! Try to Login</div>
<div class="againtext">Sign In To Your Account</div>
<article class="FormContainer">
#foreach($errors as $error)
<div class="errors">{{ $error }} </div>
#endforeach
<img class="profile-img" src="{{ URL::asset('css/avatar_2x.png')}}">
{{ Form::open(array('class'=> 'SetMe')) }}
{{ Form::text('email',null, array('placeholder'=>'Email','class'=>'insi')) }}
{{ Form::password('password',array('placeholder'=>'Password','class'=>'dnsi')) }}
{{ Form::submit('Sign In', array('class'=>'SignIn')) }}
{{ Form::close() }}
</article>
</section>
Code for AuthController.php
<?php
class AuthController extends Controller{
public function GetLogin() {
return View::make('layouts.index');
}
public function LogInfo() {
$rules = array('email' => 'required','password' =>'required');
$validator = Validator::make(Input::all(),$rules);
if($validator->fails()){
return Redirect::route('login')
->withErrors($validator);
}
else{
}
}
}
Code for Routes.php
Route::get('login', array('uses'=>'AuthController#GetLogin' ));
Route::post('login', array('uses'=>'AuthController#LogInfo'));
even when i put the Auth Code it don't show anything except "Something goes wrong". but while working with just Echos it works properly
In validation failed statement,
You need to use return Redirect::to('login') instead of return Redirect::route('login').
In index.blade.php, it should be like -
#foreach($errors->all() as $error)
<div class="errors">{{ $error }} </div>
#endforeach
instead of
#foreach($errors as $error)
<div class="errors">{{ $error }} </div>
#endforeach
Also here is my suggestion. if you are currently developing an application using laravel, it is the best to enable debug. Open laravel/app/config/app.php and make sure 'debug' => 'true'. It will help you see what is detailed error messages with stack traces.