After validation I want to pass some extra data to view. However, I can't send it.
My controller is like,
public function test()
{
$validator = Validator::make(
request()->all(),
[ 'ziptest' => 'regex:/^([0-9]{3}-[0-9]{4})$/']
);
$errors = $validator->errors();
if($errors->any()) {
return back()
->withErrors($errors)
->withTitle('Data From Controller')
->withInput();
}
return 'success';
}
In my blade I want to check if the title is passed or not. So in my blade view I have
#if($errors->any())
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
#endif
#if(isset($title))
<p>{{ $title }}</p>
#endif
However, the error portion is displaying properly. But not the title. Why is it not working?
I also tried sending the title in this way.
return back()->withErrors($errors)
->with('title','Data From Controller')
->withInput();
It is also not working.
I searched in the SO and found several similar questions regarding passing data from controller to view. However, my situation is a bit different.
In your example, you are redirecting back to the previous location. When you use with* for a redirect the information is flashed to the session, rather than made directly available to the view like it would be if you were returning a view instead.
For it to work with your example, you would have to check session('title') to get the flashed title from the redirect.
Your second approach is almost correct.
return back()->withErrors($errors)
->with([
'title' => 'Data From Controller'
])
->withInput();
note the array notation
use here array_merge method
$errors = $validator->errors();
if($errors->any()) {
$newErrors = array_merge($errors->toArray(),['title' => 'Data From Controller']);
return back()
->withErrors($newErrors)
->withInput();
}
Did you tried after validation hook but it will return data as in error bag
$validator->after(function ($validator) {
$validator->errors()->add('someField', 'Somedata');
});
And i'm wondering from where are you calling view because i saw your test() method do only validation part, with you're view you can pass data with it but with validation i think as in error bag you can send data to view.
Related
How do I use validateWithBag90 in Laravel 9? I tried a lot of combinations and I'm getting a bit frustrated.
$validator = Validator::make($request->all(), [
'old' => 'required',
'new' => 'required|string|confirmed',
]);
if ($validator->fails()) {
return redirect()->back()->with('error', $validator);
}
I'm getting this error.
Serialization of 'Closure' is not allowed
Any ideas?
Manually Creating Validators
After determining whether the request validation failed, you may use
the withErrors method to flash the error messages to the session. When
using this method, the $errors variable will automatically be shared
with your views after redirection, allowing you to easily display them
back to the user. The withErrors method accepts a validator, a
MessageBag, or a PHP array.
Instead of:
// ...
->with('error', $validator); ❌
// ...
Use this:
// ...
if ($validator->fails()) {
return redirect()
->back()
->withErrors($validator) ✅
->withInput();
}
// ...
Addendum
Displaying The Validation Errors
An $errors variable is shared with all of your application's views
by the Illuminate\View\Middleware\ShareErrorsFromSession middleware,
which is provided by the web middleware group. When this middleware is
applied an $errors variable will always be available in your views,
allowing you to conveniently assume the $errors variable is always
defined and can be safely used. The $errors variable will be an
instance of Illuminate\Support\MessageBag.
<!-- /resources/views/post/create.blade.php -->
<h1>Create Post</h1>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<!-- Create Post Form -->
Say,i have two form in one page.I have included one error blade file bellow both of the form. Now when i make wrong in one form & submit it the error message is showing bellow the both form.Its normal.But my question is, how do i separate this two error message,how can i differentiate by giving them two different name?
Give this a try
return redirect()->back()->withErrors([
'form1.name' => 'name is required in Form 1',
'form1.email' => 'email is required in Form 1',
'form2.city' => 'city is required in form 2'
]);
in your view
#if($errors->any())
#foreach ($errors->get('form1.*') as $error) {
{{ $error }}
#endforeach
#endif
So you can group errors by form using array notation form.name and get all with $errors->get('form.*).
Read more about errors here: https://laravel.com/docs/5.4/validation#working-with-error-messages
If you're using Form Request Validation, you can change the errorBag property to get a unique array of errors for your view file.
In your Request file:
class MyFormRequest {
protected $errorBag = 'foobar';
public function rules() { // ... }
}
In your controller:
public function store(MyFormRequest $request) {
// Store entry.
}
Then in your view file:
#if ($errors->foobar->isNotEmpty())
// Work with the errors
#endif
You can use the named error bags.
$validator = Validator::make($request->all(), [
'field1' => 'required',
'field2' => 'required|digits:1',
]);
if ($validator->fails()) {
return back()
->withErrors($validator, 'form1error')
->withInput();
}
To print the error in blade file use-
#if(count($errors->form1error)>0)
<ul>
#foreach($errors->form1error->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
#endif
I have the following code which sends a passowrds recovery mail:
public function recovery(Request $request)
{
$validator = Validator::make($request->only('email'), [
'email' => 'required'
]);
if($validator->fails()) {
throw new ValidationHttpException($validator->errors()->all());
}
$response = Password::sendResetLink($request->only('email'), function (Message $message) {
$message->subject(Config::get('boilerplate.recovery_email_subject'));
});
switch ($response) {
case Password::RESET_LINK_SENT:
return $this->response->noContent();
case Password::INVALID_USER:
return $this->response->errorNotFound();
}
}
Which I found out uses the following template: resources/views/auth/emails/password.php
which is an empty file.
How I can access the token from this template?
Isn't there any built-in view to use from laravel?
The function in your questions doesn't return a view.
Also, I'm unfamiliar with that path to the view that is in your question. Which version of Laravel are you using?
Anyhow, you can get the reset token from the DB, just like any other value in the DB. E.g. from a controller that is returning a view:
$user = User::find(Auth::id());
$remeber_token = $user->remember_token;
return view('to_your_view.blade.php', compact('remember_token');
And then in the view file:
{{ $remember_token }}
This will output it, no need to use echo or anything.
But, again, the function you pasted into your question is not a function that is returning a view, so I'm not sure where to tell you to put the above code.
As for your questoin about Laravel having an in-built view for 'this', in Laravel 5.3, at least, the view I assume you want will be within `resources/views/auth/passwords/'.
I have stack of calls in controller:
if ($validator->fails()) {
return Redirect::back()
->withErrors($validator)
->withInput();
}
The function withErrors takes array of errors.
How can I display there messages in template?
I tried:
{{Session::get('MessageBag')}}
So, the latest edition is:
$errors = $validator->messages(); // Here I get $error with fillied data
return redirect('tour/create')
->withErrors($errors)
->withInput();
In template I do:
{{count($errors)}}
It gives me zero
In view file access errors with $errors
{{$errors->first('MessageBag')}}
Try to print $errors print_r($errors). It is global variable for views.
Try this you can see whether the data is available
{{ dd(Request::session()) }}
I make my view in the controller via:
$data = Lib::index();
$view = View::make('index')
->with('data', $data)
->render();
return $view;
I can check if data is empty in the controller via:
$data->isEmpty();
But when I try the same thing in the view I get the error:
Call to a member function isEmpty() on a non-object
Why?
Here's the code for Lib::index():
$page = isset($_GET['page']) ? ($_GET['page']) : 1;
Paginator::setCurrentPage($page);
try {
$data = Asset::with(array('sizes'=> function($query){
$query->select('width', 'height', 'asset_id');
}))->where('active', 1)->orderBy('updated_at', 'DESC')->paginate(Config::get('p.results_per_page'), array('id', 'alt'));
}
catch (QueryException $e) {
App::abort(404);
}
return $data;
isEmpty() is a Collection method. For some weird reasons, in views, it sometimes refer to an empty Collection as null. The safest check, in my opinion would be to do a counts check, like so:
if (count($data)) {...}
This works well both in Controllers and Views.
consider you are getting some information as collection;
$UserInfo = User::where('phone', $phone_number)->first();
use this code to for error check
if(empty($UserInfo)){
return redirect()->back()->withErrors('we don't have a user with this phone number ');
}
and add below code into your blade
#if(count($errors)>0)
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
#endif
best regards
Try
> var_dump($data);
in the view.
See what it shows up. This might help further investigate the error.
Then In accordance go ahead with
> foreach($data as $moredata){
> $moredata->isEmpty(); }
Should work.