Can someone explain me why sometimes I have to use $errors->all() and sometimes not?
Struggling to find a unique solution for array of error and object $errors.
// View 1
#if (count($errors) > 0)
#foreach($errors as $error)
{{ $error }}<br>
#endforeach
#endif
// View 2 that sometimes it crashes with:
// "Call to a member function all() on array"
#if (count($errors) > 0)
#foreach($errors->all() as $error)
{{ $error }}<br>
#endforeach
#endif
$errors->all() using if you validate data via Validator or in the Request class. See this part of the documentation. Laravel share $errors variable as MessageBag class.
$errors as array using if in the controller you return something like this:
return back()->withErrors([
'field1' => 'Error in the field 1'
]);
In this case Laravel share $errors variable as array
I don't really do laravel that much but I assume you can always do something like this:
#if (count($errors) > 0)
#if(is_array($errors))
#foreach($errors as $error)
// code
#endforeach
#elseif(is_object($errors))
#foreach($errors->all() as $error)
//code
#endforeach
#endif
#endif
Related
I am using Laravel Framework 8.62.0.
I am validating a form the following way:
$validator = Validator::make($request->all(), [
'title_field' => 'required|min:3|max:100',
'comment_textarea' => 'max:800',
'front_image' => 'required|mimes:jpg,jpeg,png,bmp,tif',
'back_image' => 'required|mimes:jpg,jpeg,png,bmp,tif',
'price' => "required|numeric|gt:0",
'sticker_numb' => "required|numeric|gt:0",
'terms-checkbox' => "accepted",
]);
if ($validator->fails()) {
// Ooops.. something went wrong
return Redirect::back()->withInput();//->withErrors($this->messageBag);
}
I want to display errors in the frontend the following way:
#if ($errors->any())
<div class="alert alert-danger alert-dismissable margin5">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<strong>Errors:</strong> Please check below for errors
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
However, my $error variable is emtpy, when validation errors exist, so the validation errors do not get shown in my frontend.
Any suggestions what I am doing wrong?
I appreciate your replies!
You should pass the $validator to withErrors like:
if ($validator->fails()) {
// Ooops.. something went wrong
return Redirect::back()->withErrors($validator)->withInput();
}
That's because your not passing errors.
Try this:
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput();
}
As the previous speakers said, you must of course return the errors. but you can also use the Request Validate Helper. it does this automatically.
$request->validate([...])
As soon as an error occurs, it returns a response with the errors.
https://laravel.com/docs/8.x/validation#quick-writing-the-validation-logic
In my laravel application, I'm having a list of regions in my DB
This is my controller method
public function index()
{
$region_options = Region::get();
return view('home',compact('region_options'));
}
and I have following in my blade,
#if(!$region_options->isEmpty())
<ol class="region-pop">
#foreach ($region_options as $key => $region)
<li>{{ $region->name }}</li>
#endforeach
</ol>
#endif
But when I run this it gave me an error saying, Undefined variable: region_options
I'm struggling to find what the issue is...
my validation is working correctly. but didn't show any message. I mention the below.
in controller
$fields = collect([
'monthly_fees',
'admission',
'due_advance',
'session_fee',
'library',
'sports',
'poor_funds',
'fine',
'reciept',
'milad',
'scout',
'development',
'registration',
'f_tutorial',
's_tutorial',
't_tutorial',
'f_exam',
's_exam',
't_exam',
'labratory',
'transport',
'syllabus',
'certificate',
'testimonial',
'generator',
'extra'
]);
$rules = $fields->mapWithKeys(function ($field) use ($fields) {
return [
$field => 'required_without_all:' . $fields->reject(function ($item) use ($field) {
return $item == $field;
})->implode(',')
];
})->toArray();
$this->validate($request, $rules);
in views
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul class="text-center">
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
I also use these lines of codes in the controller but didn't work.
if($this->validate()->fails()) {
return redirect()->back()->with('error','Please Input minimum 1 field...');
}
I want to do minimum 1 field is required. I have 26 input fields. I always use these codes for single use. but this time want to validate minimum One field required. These codes validate the required but didn't show any messages though I mentioned the errors in blade. can you please help me with these errors? thanks in advance.
I solved my problems. here i used $this->vatidate(...);
it was wrong for me. then I used Validator package and returns a custom message with redirect if fails. then it works.
So I know about passing variables via the controller for instance if its a query array I will do
public function index()
{
$query = Request::get('q');
if ($query) {
$users = User::where('username', 'LIKE', "%$query%")->get();
}
return view('view', compact('users'));
}
And when on the blade I will do
#if( ! empty($users))
#foreach($users as $user)
{{ $user->username }}
#endforeach
#endif
Now my question is how do I set a variable using a variable from the foreach? at the moment I am using PHP inside of the blade template file but I feel this is messy, here is what I have
#if( ! empty($users))
#foreach($users as $user)
<?php
$lastOnline = \Carbon\Carbon::createFromTimeStamp(strtotime($user->last_online))->diffForHumans();
$fiveMinsAgo = \Carbon\Carbon::now()->subMinute(5);
?>
{{ $user->username }}
#if ($user->last_online <= $fiveMinsAgo)
{{ $lastOnline }}
#else
Online Now
#endif
#endforeach
#endif
found a solution to my issue if anyone else is ever looking for it.
public function getLastOnlineAttribute($value)
{
$fiveMinsAgo = \Carbon\Carbon::now()->subMinute(5);
$thirtMinsAgo = \Carbon\Carbon::now()->subMinute(30);
$lastOnline = \Carbon\Carbon::createFromTimeStamp(strtotime($value))->diffForHumans();
if ($value <= $fiveMinsAgo) {
echo 'Last Active: '.$lastOnline.'';
}
else {
echo 'Online Now';
}
}
Basically add this into your model for the variable (eg, if its a $user->last_online it would go into the user model) , it is called a eloquent mutator if you are ever looking for more info, https://laravel.com/docs/master/eloquent-mutators
It grabs your data for the variable for instance {{ $user->last_online }}
Note that the Underscore is transformed into a CamelCase in the function name, the output is set at $value, you can then set variables inside of the function and mould the output however you wish, then in the blade you can get rid of all the extra crap and just use {{ $user->last_online }}
The problem is that withErrors() is working perfectly in this code, but withMessage() isn't.
I also tried with('message', 'Test message!'). In views file, I can retrieve withErrors using $errors variable, but if I want to retrieve withMessage, I have to use Session::get('message'). Why is $message not working?
Controller:
public function registration() {
$rules = array(...);
$validator = Validator::make(Input::all(), $rules);
if($validator->fails()) {
return Redirect::route('registration')->withErrors($validator);
}
else {
//Some code here...
return Redirect::route('registration')->withMessage('Test message!');
}
}
Template:
#extends('default.base')
#section('main')
#if(!empty($errors->all()))
<div class="alert alert-danger" role="alert">
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}
#endforeach
</ul>
</div>
#endif
#if(isset($message))
{{ $message }}
#endif
#stop
That is because errors is a special case. When creating a view, Laravel check's if there is a session variable with the name errors. If so it will then pass the contents as $errors to the view.
Illuminate\View\ViewServiceProvider#registerSessionBinder
if ($me->sessionHasErrors($app))
{
$errors = $app['session.store']->get('errors');
$app['view']->share('errors', $errors);
}
This means you either use Session::has('message') and Session::get('message') in your view or you add a View Composer that does basically the same that Laravel does with errors:
View::composer('*', function($view){
if(Session::has('message')){
$view->with('message', Session::get('message'));
}
});