Laravel validation errors are appearing randomly in my view - validation

When I submit my form the validation works randomly, I mean that it sometimes appears and sometimes not, I found out that the validation object is returned by controller but it is not looped in my view always.
here is my code in view:
#if ($errors->any())
<ul class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</ul>
#endif
it randomly shows this:
object(Illuminate\Support\ViewErrorBag)#651 (1) { ["bags":protected]=> array(1) { ["default"]=> object(Illuminate\Support\MessageBag)#643 (2) { ["messages":protected]=> array(12) { ["province_code"]=> array(1) { [0]=> string(36) "The province code field is required." } ["district_code"]=> array(1) { [0]=> string(36) "The district code field is required." } ["training_provider"]=> array(1) { [0]=> string(40) "The training provider field is required." } ["training_center"]=> array(1) { [0]=> string(38) "The training center field is required." } ["classroom"]=> array(1) { [0]=> string(32) "The classroom field is required." } ["course_leader"]=> array(1) { [0]=> string(36) "The course leader field is required." } ["shift"]=> array(1) { [0]=> string(28) "The shift field is required." } ["start_date"]=> array(1) { [0]=> string(33) "The start date field is required." } ["end_date"]=> array(1) { [0]=> string(31) "The end date field is required." } ["start_time"]=> array(1) { [0]=> string(33) "The start time field is required." } ["end_time"]=> array(1) { [0]=> string(31) "The end time field is required." } ["course_conduct_days"]=> array(1) { [0]=> string(42) "The course conduct days field is required." } } ["format":protected]=> string(8) ":message" } } }<!DOCTYPE html>
and then it comes up with empty array!
object(Illuminate\Support\ViewErrorBag)#652 (1) { ["bags":protected]=> array(0) { } }

Do this if the message bag has errors then only they would be printed
#if($errors->has())
<div class="alert alert-danger">
<ul>
#foreach($errors->getMessages() as $messages)
#foreach($messages as $message)
<li>{{$message}}</li>
#endforeach
#endforeach
</ul>
</div>
#endif
Thanks :)

finally I solved this problem, it was a conflict with ajax

Related

Message not appear on page after function is performed in laravel

Maybe is something simple but can't understand why I don't see my message.
I have this in the controller after the function is submitted
return redirect()->route('item.show', $id)->with('alert-success', ' Review submitted successfully.');
And this in item page
#foreach (['danger', 'warning', 'success', 'info','message'] as $msg)
#if(Session::has('alert-' . $msg))
<p class="alert alert-{{ $msg }}">{{ Session::get('alert-' . $msg) }} ×</p>
#endif
#endforeach
The form is submitted successfully, data is saved in the database, the page is reloaded but the message does not appear for success.
update
array(4) {
["_token"]=>
string(40) "snB4uoaR087wrvXOuh8epR56cjtC2OCSmZJd9smn"
["_previous"]=>
array(1) {
["url"]=>
string(29) "http://example.com/item/17"
}
["flash"]=>
array(2) {
["old"]=>
array(0) {
}
["new"]=>
array(0) {
}
}
["login_web_59ba36addc2b2f9401580f014c7f58ea4e30989d"]=>
int(9)
}
Route
Route::group(['namespace' => 'Frontend', 'middleware' => 'web'], function () {
Route::post('items/review/{item}', 'ItemController#reviewSubmit')->name('item.review');
....
}
Use flash for message stuffs:
Controller
$request->flash('alert-success', ' Review submitted successfully.');
return redirect()->route('item.show', $id);
item page:
<div class="flash-message">
#foreach (['danger', 'warning', 'success', 'info'] as $msg)
#if(Session::has('alert-' . $msg))
<p class="alert alert-{{ $msg }}">{{ Session::get('alert-' . $msg) }} ×</p>
#endif
#endforeach
</div>
Check about flash message with laravel documentation
NOTE: Make sure the middleware not applied twice, this is also be the cause of this issue. Check this

Laravel 5.2 Flash Old and errors empty after redirect

I have a problem in laravel. This problem it's only in production server, in my local server it's work property. So maybe it's something in the configuration that I don't know.
So when I Send a form, with wrong values the laravel validator system should redirect the user to the form and show the errors.
This is the code my controller:
$rules = array(
'nombre' => 'required|min:3|max:80',
'email' => 'required|email',
'asunto'=>'required|min:3|max:200',
'mensaje'=>'required|min:5|max:1000',
//'g-recaptcha-response' => 'required|recaptcha',
);
$validation = Validator::make($request->all(), $rules);
//si la validación falla redirigimos al formulario de registro con los errores
//y con los campos que nos habia llenado el usuario
if ($validation->fails())
{
return Redirect::to('/#contacto')->withErrors($validation->messages())->withInput();
}
/#contacto is the Home route with the anchor contacto so this should redirect to the home. This is ok.
This is my route.php
Route::get('/', function () {
return view('web.index');
});
Route::post('/contacto/enviar', 'WebController#contacto');
This is my Kernel
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
];
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
],
'api' => [
'throttle:60,1',
],
];
This is my view that should show the error result.
<form name="contacto" method="post" action="/contacto/enviar"><input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
<div class="col-lg-6 col-sm-5 wow fadeInUp delay-05s">
<div class="form"><font color="#ff0000" size="1"><b>{{$errors->first('nombre', ':message')}}</b></font><input class="input-text" type="text" name="nombre" value="<?=Request::old('nombre', 'Nombre y apellido *');?>" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;"><font color="#ff0000" size="1"><b>{{$errors->first('email', ':message')}}</b></font><input class="input-text" type="text" name="email" value="<?=Request::old('email', 'Correo electrónico *');?>" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;"><font color="#ff0000" size="1"><b>{{$errors->first('telefono', ':message')}}</b></font><br><input class="input-text" type="text" name="telefono" value="<?=Request::old('telefono', 'Teléfono (incluya código de área) *');?>" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;"><font color="#ff0000" size="1"><b>{{$errors->first('asunto', ':message')}}</b></font><input class="input-text" type="text" name="asunto" value="<?=Request::old('asunto', 'Asunto');?>" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;"><font color="#ff0000" size="1"><b>{{$errors->first('mensaje', ':message')}}</b></font><textarea class="input-text text-area" cols="0" rows="0" name="mensaje" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;"><?=Request::old('mensaje', 'Escriba aquí el mensaje *');?></textarea><font color="#ff0000" size="1"><b>{{$errors->first('g-recaptcha-response', ':message')}}</b></font>{!! Recaptcha::render(['lang'=>'es']) !!}<input class="input-btn" type="submit" value="ENVIAR"></div>
</div></form>
On the top of my view I have a var_dump(Session::all()) and this is the result allways when I submit the form.
array(3) {
["_token"]=>
string(40) "WrQWk9qTH47QrKD6J0Qld8sOhKcUp8xssGpy0F2g"
["_previous"]=>
array(1) {
["url"]=>
string(25) "http://dsnet.dsnet.com.ar"
}
["flash"]=>
array(2) {
["old"]=>
array(0) {
}
["new"]=>
array(0) {
}
}
In execution of php artisan route:list this is my result, so I have checked that the web middleware is not duplicate.
The estrange thing is that the same code in my local server is working, and in all the form redirect the result are:
array(4) {
["_token"]=>
string(40) "4s1rhoydlH7l84Em792N79ymemNjh4Ep6I8WLNSG"
["errors"]=>
object(Illuminate\Support\ViewErrorBag)#177 (1) {
["bags":protected]=>
array(1) {
["default"]=>
object(Illuminate\Support\MessageBag)#178 (2) {
["messages":protected]=>
array(1) {
["email"]=>
array(1) {
[0]=>
string(40) "The email must be a valid email address."
}
}
["format":protected]=>
string(8) ":message"
}
}
}
["flash"]=>
array(2) {
["new"]=>
array(0) {
}
["old"]=>
array(2) {
[0]=>
string(6) "errors"
[1]=>
string(10) "_old_input"
}
}
["_old_input"]=>
array(7) {
["_token"]=>
string(40) "jzCq4CGGgutPJ3qB2ls1rp7uaiHpcra9Aer1vApC"
["nombre"]=>
string(19) "Nombre y apellido *"
["email"]=>
string(21) "Correo electrónico *"
["telefono"]=>
string(38) "Teléfono (incluya código de área) *"
["asunto"]=>
string(6) "Asunto"
["mensaje"]=>
string(26) "Escriba aquí el mensaje *"
["g-recaptcha-response"]=>
string(0) ""
}
}
I remember that I had the same issue in the local server and I fixed setting the domain configuration on the session config file as null, but this solution doesn't work in the production server. Any Idea?
Finally, I say that the code it's great! There is not problem with the code, but is a problem with the server configuration. I don't know where. But I upload the site to another server and with the setting of the domain = null, of the session configuration work great.

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

Resolving unforeseen view matter for calling function from view

I am having some real difficult resolving an issue. Basically I person will search for a room and I will display a list (including pagination) of rooms matching the criteria. Now the issue arises when I try to call for the room's image. The first image will display but the rest wont, I get the error:
A PHP Error was encountered Severity: Notice
Message: Undefined offset: 0
Filename: views/search_view.php
Line Number: 27
A PHP Error was encountered Severity: Notice
Message: Trying to get property of non-object
Filename: views/search_view.php
Line Number: 27
This is what I have done so far
My Model:
function get_room_image($rid)
{
$q = $this->db
->where('room_id',$rid)
->limit(1)
->get('room_image');
return $q->result();
}
function search_rooms()
{
$q = $this->db
->where('features', $this->input->post('features'))
->get('rooms');
$room['results'] = $q->result();
return $room['results'];
}
My Controller:
function search()
{
$data['main_content'] = 'search_view';
$data['page_title'] = 'Search';
$data['results'] = $this->site_model->search_rooms();
$this->load->view('includes/template',$data);
}
My View:
...
<?php foreach ($results['results'] as $room) {
$room_images = $this->site_model->get_room_image($room->id); ?>
<div class="col2 bot">
<div class="col_head"></div>
<div class="col_info">
<table border="0" cellpadding="5" cellspacing="5">
<tr><td>
<img src="<?php echo base_url() . 'room/' . $room_images[0]->image_name; ?>" border="0" class="imgbox" />
</td>
...
Line 27 is actually the line with the img tag on it
When I do a var_dump as requested I get the following:
array(1) {
[0]=>
object(stdClass)#27 (3) {
["id"]=>
string(1) "1"
["room_id"]=>
string(1) "1"
["image_name"]=>
string(36) "1614d828817ac5b396660621048b167a.jpg"
}
}
array(0) {}
array(0) {}
array(0) {}
...
SO it seems that it isn't performing the get_room_image function on each iteration correctly
Any advice is most welcome.
Regards,
First,I don't think that you should be calling the model from within the view. You should call the model from within the controller and pass it to your view. Another SO post that talks about that: https://stackoverflow.com/a/1733309/1260593
You should try to perform a join on the tables in your model.
Model:
function search_rooms()
{
$q = $this->db
->select('*')
->from('rooms')
->where('features', $this->input->post('features'))
->join('room_image', 'rooms.id = room_image.room_id');
return $q;
}
Controller:
$data['main_content'] = 'search_view';
$data['page_title'] = 'Search';
$data['results'] = $this->site_model->search_rooms();
$this->load->view('includes/template',$data);
View:
<?php foreach ($results->result() as $room) {
$image = $room->image_name;
<div class="col2 bot">
<div class="col_head"></div>
<div class="col_info">
<table border="0" cellpadding="5" cellspacing="5">
<tr><td>
<img src="<?php echo base_url() . 'room/' . $image; ?>" border="0" class="imgbox" />
</td>
}
Issue was resolved as I forgot to add a ";" onto a line within my db query string

Code Igniter: Upload multiple images

My codes:
View
<?php echo form_open_multipart('projects/create') ?>
<label for="pro_video">Project Image</label>
<?php echo form_upload(array('name'=>'pro_image', 'type'=>'file', 'multiple'=>'multiple', 'accept'=>'image/*'))?>
<input type="submit" name="create_project" value="Create" />
</form>
Controller
public function __construct()
{
parent::__construct();
$this->load->library('image_lib');
$this->load->helper(array('form', 'url', 'html'));
$this->load->library('form_validation');
}
public function create()
{
if( sizeof($_FILES['pro_image']) > 0 ){
$config['upload_path'] = './test_upload/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->load->library('upload', $config);
$this->image_lib->initialize($config);
for( $i = 0; $i < sizeof($_FILES['pro_image']['name']); $i++ ){
$this->upload->do_upload('pro_image');
}
}
}
but it upload last image.. :(
on var_dump($_FILES):
array(1) {
["pro_image"]=>
array(5) {
["name"]=>
array(2) {
[0]=>
string(10) "Desert.jpg"
[1]=>
string(10) "Tulips.jpg"
}
["type"]=>
array(2) {
[0]=>
string(10) "image/jpeg"
[1]=>
string(10) "image/jpeg"
}
["tmp_name"]=>
array(2) {
[0]=>
string(23) "E:\wamp\tmp\phpA235.tmp"
[1]=>
string(23) "E:\wamp\tmp\phpA245.tmp"
}
["error"]=>
array(2) {
[0]=>
int(0)
[1]=>
int(0)
}
["size"]=>
array(2) {
[0]=>
int(845941)
[1]=>
int(620888)
}
}
}
Thanks friends I used HTML5 file tag

Resources