Reputation: 1536
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.
Upvotes: 2
Views: 1911
Reputation: 3274
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.
Upvotes: 0
Reputation: 12460
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.
Upvotes: 2
Reputation: 15115
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();
}
Upvotes: 0
Reputation: 4499
Your second approach is almost correct.
return back()->withErrors($errors)
->with([
'title' => 'Data From Controller'
])
->withInput();
note the array notation
Upvotes: 1