How to display error with Session:get() and withErrors()? - laravel

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()) }}

Related

Laravel: How to pass a collection to view?

The $result variable displays the json-string correctly. And when I try to send the result to the view, I get an error.
$accreditations = Accreditation::with(['country'])->get();
$result = AccreditationResource::collection($accreditations);
//return $result;
//{"data":[{"id":5,"user_id":1,"login":"Admin","country_id":"4","country":{"id":4,"name":"Austria"}}]}
return View::make('accred_table', $result->login);
//Error 500: Property [login] does not exist on this collection instance.
Help me figure this out
$result is an array. So, there is no login as the error said. If you return only one record from AccreditationResource, you can use
return view('accred_table', ['login' => $result[0]['login']]);
In blade, you will have $login.

Problem on setting error message if insert fails

When doing add activity inside store method, after passing validation I am calling a method that returns success or failure.
But on failure, I am not able to handle the code properly.
If I redirect, am not getting the old value.
So How do i return to create method with error message & old value both?
Any way to populate the $errors array?
Am new to Laravel. Thanks in advance
public function store(Request $request, AppMailer $mailer)
{
$validatedData=$request->validate([
.......
........
]);
$tracking_model = new Tracking;
$result = $tracking_model->add($request->all());
if ($result === true) {
return redirect('posts')->with('success', 'Created Successfully');
}
else{
$err_msgs = $result;
//what to do here ???????
// return redirect('posts/create')->with('error', $err_msgs);
}
}
try this
in the controller
return redirect('posts/create')->withInput()->withErrors($err_msgs);
and in view .blade
#if ($errors->any())
#foreach ($errors as $error)
...
#endforeach
#else
No tags
#endif

How to pass extra data after validation?

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.

Laravel password recovery template

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/'.

laravel validation output in ::back controller

Let me tell you my situation. I have made a simple library/module which I can popupulate in my controller. This way I can use one view file and have different results just by changing some of the $form fields(like text inputs, selects, etc). The example is below:
$form = new FormHelper('Webshop bewerken','shop/update',$errors);
$form->addHiddenInput('id',$id);
$form->addTextInput('name','Naam',$item->name);
$form->addTextInput('export','Uitvoer',$item->output_location);
$form->addTextInput('method','Methode',$item->method);
$form->addSidebar();
$form->generateForm();
//show the page
$this->layout->content = View::make('item')->with('form',$form);
The problem exist not within the form. This works fine until i need to validate. However the $errors is undefined so i cannot render the errors.
I have noticed that this variable is only available in the view and not in the controller.
This is fine if you have just a few blade.php files but not in my case(many many screens with generic information).
How can I access the $errors variable (output from the laravel validator) in a controller and not view?
Below is a validator code example i use:
//run the validator
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::back()->withInput()->withErrors($validator);
} else {
//do something else(not relevant)
}
In your controller you may use:
$validator = Validator::make(Input::all(), $rules);
$errors = $validator->errors();
This will give you the same errors that you get in the view. To access a particular error you may use:
$error = $validator->errors('someFormFieldName')->first();

Resources