LARAVEL get result of withErrors in view - php

in controller i'm using:
if ($validator->fails())
{
return Redirect::to('/admin/profile')
->withErrors($validator)
->withInput();
}
how to get result of withErrors in view ?
{{ $errors->all() }}

If you want to show all errors in one place you can use
#foreach ($errors->all() as $error)
<div>{{ $error }}</div>
#endforeach
If you want to show each field's errors e.g. bellow the field you can use (e.g. for email)
{{ $errors->first('email') }}
we use first() in order to show only one error each time for each field.

Related

Laravel 5.4 display errors in view

I have a form where I upload a file.
In the controller I do all kinds of checks on columns in this file and get some errors.
I add these errors to an array and I want to display all these errors in the view.
I tried all kinds of solution but nothing works.
Right now, I'm doing this in the controller for each line in the file:
$errors[] = array('file_name'=>$file_name, 'error'=>'Invalid coffee name');
And in the view I try these two things:
#if ($errors->any())
{{ implode('', $errors->all('<div>:message</div>')) }}
#endif
#if ($errors->any())
#foreach ($errors->all() as $error)
<div>{{$error}}</div>
#endforeach
#endif
The problem is, although I have 2 errors in the errors array (I checked), I only see the last one in the view.
What am I doing wrong?
I solved it like this:
In my controller method I added:
$errors = new MessageBag();
When I have an error:
$errors->add('coffee', $file_name . ': Invalid coffee name');
In the view:
#if ($errors->any())
<div class="alert alert-danger">
<p>There are errors in the file you uploaded</p>
<ul>
#foreach ($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
#endif

how to validate (check) data table values befour data insert in Laravel 5.2

I need validate and generate error message if same user try to insert existing project_name to the table in Laravel 5.2. My project table like this
user_id project_name
1 abc
2 sdf
3 kju
My project data store controller as follow
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|min:3'
]);
$project = new Project;
$project->project_name = $request->input('name');
$project->user_id = Auth::user()->id;
$project->save();
return redirect()->route('projects.index')->with('info','Your Project has been created successfully');
}
and I have alert.blade.php file as
#if ( session()->has('info'))
<div class="alert alert-info" role-"alert">
{{ session()->get('info') }}
</div>
#endif
#if ( session()->has('warning'))
<div class="alert alert-danger" role-"alert">
{{ session()->get('warning') }}
</div>
#endif
how can I do this?
If your form validation is failed then a 422(Unprocessable) response is returned by laravel. And an $error variable will be available in the response. So you can check if the variable is empty or not, and you can display the errors.
Like Below code. This is from laravel 5.2 documentation.
<!-- /resources/views/post/create.blade.php -->
<h1>Create Post</h1>
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<!-- Create Post Form -->
https://laravel.com/docs/5.2/validation
You could foreach the variable $errors if you want catch the error message,
or if you are asking the validation rule, you could use 'exists:database'
https://laravel.com/docs/5.2/validation#rule-exists

Laravel 5.2 redirect back with success message

I'm trying to get a success message back to my home page on laravel.
return redirect()->back()->withSuccess('IT WORKS!');
For some reason the variable $success doesn't get any value after running this code.
The code I'm using to display the succes message:
#if (!empty($success))
<h1>{{$success}}</h1>
#endif
I have added the home and newsletter page to the web middleware group in routes.php like this:
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::get('/', function () {
return view('home');
});
Route::post('/newsletter/subscribe','NewsletterController#subscribe');
});
Does anyone have any idea why this doesn't seem to work?
You should remove web middleware from routes.php. Adding web middleware manually causes session and request related problems in Laravel 5.2.27 and higher.
If it didn't help (still, keep routes.php without web middleware), you can try little bit different approach:
return redirect()->back()->with('message', 'IT WORKS!');
Displaying message if it exists:
#if(session()->has('message'))
<div class="alert alert-success">
{{ session()->get('message') }}
</div>
#endif
you can use this :
return redirect()->back()->withSuccess('IT WORKS!');
and use this in your view :
#if(session('success'))
<h1>{{session('success')}}</h1>
#endif
Controller:
return redirect()->route('subscriptions.index')->withSuccess(['Success Message here!']);
Blade
#if (session()->has('success'))
<div class="alert alert-success">
#if(is_array(session('success')))
<ul>
#foreach (session('success') as $message)
<li>{{ $message }}</li>
#endforeach
</ul>
#else
{{ session('success') }}
#endif
</div>
#endif
You can always save this part as separate blade file and include it easily.
fore example:
<div class="row">
<div class="col-md-6">
#include('admin.system.success')
<div class="box box-widget">
You can simply use back() function to redirect no need to use redirect()->back() make sure you are using 5.2 or greater than 5.2 version.
You can replace your code to below code.
return back()->with('message', 'WORKS!');
In the view file replace below code.
#if(session()->has('message'))
<div class="alert alert-success">
{{ session()->get('message') }}
</div>
#endif
For more detail, you can read here
back() is just a helper function. It's doing the same thing as redirect()->back()
One way to do that is sending the message in the session like this:
Controller:
return redirect()->back()->with('success', 'IT WORKS!');
View:
#if (session()->has('success'))
<h1>{{ session('success') }}</h1>
#endif
And other way to do that is just creating the session and put the text in the view directly:
Controller:
return redirect()->back()->with('success', true);
View:
#if (session()->has('success'))
<h1>IT WORKS!</h1>
#endif
You can check the full documentation here: Redirecting With Flashed Session Data
I hope it is very helpful, regards.
All of the above are correct, but try this straight one-liner:
{{session()->has('message') ? session()->get('message') : ''}}
In Controller
return redirect()->route('company')->with('update', 'Content has been updated successfully!');
In view
#if (session('update'))
<div class="alert alert-success alert-dismissable custom-success-box" style="margin: 15px;">
×
<strong> {{ session('update') }} </strong>
</div>
#endif
You can use laravel MessageBag to add our own messages to existing messages.
To use MessageBag you need to use:
use Illuminate\Support\MessageBag;
In the controller:
MessageBag $message_bag
$message_bag->add('message', trans('auth.confirmation-success'));
return redirect('login')->withSuccess($message_bag);
Hope it will help some one.
Adi
in Controller:
`return redirect()->route('car.index')->withSuccess('Bein ajoute')`;
In view
#if(Session::get('success'))
<div class="alert alert-success">
{{session::get('success')}}
</div>
#endif

In October CMS, How to redirect from a plugin to a page with data

I'm creating a plugin for October CMS that has a frontend form (component) with
{{ form_open({ request: 'onSubmitForm' }) }}
In the plugin there is a function onSubmitForm() with a validator.
If the validator fails I want to redirect to the page the form input came from ($this->page->url) but send the validator messages ($validator->messages()) and the original input of the form (post()) with it.
I've tried:
if ($validator->fails()) {
return Redirect::to($this->page->url)->withErrors($validator->messages())->withInput(post());
}
and if I put {{ errors }} on the page i do get a message
Object of class Illuminate\Support\ViewErrorBag could not be converted
to string
which I then fixed by using:
{% for error in errors.all() %}
<li>{{ error }}</li>
{% endfor %}
and {{ errors.first('name') }}
but the {{ input }} doesn't even return an error.
Am I doing the redirecting wrong? Or does it have to do with how Twig and Blade are so completely different? Is there a way to prefill old input values and error messages?
You can output the old input value with this twig
{{form_value('my_input_name')}}
october cms form doc
As you can read in the very top you can "translate" php exemple to twig by changing "method name" to lower case and "::" to _
exemple:
// PHP
<?= Form::open(..) ?>
// Twig
{{ form_open(...) }}
hope it will help.
this is my regular code for blade
#if (count($errors) > 0)
<div class="alert alert-danger">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<strong>{{trans('messages.sorry')}}</strong>
<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Instead of redirecting to the same page where the form was submitted from, just use Ajax! You can do in couple ways.
instead of form_open, use form_ajax.
Here is an example:
form_ajax('onSubmitForm', { model: user, class: 'whateverclass', id: 'idoftheform', success:'doSomethingInJS(textStatus, data)'})
in PHP, you can return your error message as
return ["ErrorMsg" => 'this is some error']
Then in JS you can display it:
function whateverClass (textStatus, data){
alert (data.ErrorMsg);
$('#alertHolderDiv').html(data.ErrorMsg);
}
another way would be to use a partial! And once you throw an error you can use "update" in ajax command to update the partial. The partial will be overwritten with the new message.

Laravel Getting Error with Validations

I am trying to Get Validation Errors on index.blade.php having issues:
When I fill both the fields then it goes well if i just put an Echo or Return in getLogin Controller.
When I just fill one field and it works good if i just put and echo or Return but not giving validation errors, with Validation Errors it only shows, "Something went Wrong"
Code for index.blade.php
<section class="mainWrap">
<div class="headingfirst"><img src="{{ URL::asset('css/des.png') }}" width="78"></div>
<div class="sedhead">Hey User!!!! Try to Login</div>
<div class="againtext">Sign In To Your Account</div>
<article class="FormContainer">
#foreach($errors as $error)
<div class="errors">{{ $error }} </div>
#endforeach
<img class="profile-img" src="{{ URL::asset('css/avatar_2x.png')}}">
{{ Form::open(array('class'=> 'SetMe')) }}
{{ Form::text('email',null, array('placeholder'=>'Email','class'=>'insi')) }}
{{ Form::password('password',array('placeholder'=>'Password','class'=>'dnsi')) }}
{{ Form::submit('Sign In', array('class'=>'SignIn')) }}
{{ Form::close() }}
</article>
</section>
Code for AuthController.php
<?php
class AuthController extends Controller{
public function GetLogin() {
return View::make('layouts.index');
}
public function LogInfo() {
$rules = array('email' => 'required','password' =>'required');
$validator = Validator::make(Input::all(),$rules);
if($validator->fails()){
return Redirect::route('login')
->withErrors($validator);
}
else{
}
}
}
Code for Routes.php
Route::get('login', array('uses'=>'AuthController#GetLogin' ));
Route::post('login', array('uses'=>'AuthController#LogInfo'));
even when i put the Auth Code it don't show anything except "Something goes wrong". but while working with just Echos it works properly
In validation failed statement,
You need to use return Redirect::to('login') instead of return Redirect::route('login').
In index.blade.php, it should be like -
#foreach($errors->all() as $error)
<div class="errors">{{ $error }} </div>
#endforeach
instead of
#foreach($errors as $error)
<div class="errors">{{ $error }} </div>
#endforeach
Also here is my suggestion. if you are currently developing an application using laravel, it is the best to enable debug. Open laravel/app/config/app.php and make sure 'debug' => 'true'. It will help you see what is detailed error messages with stack traces.

Categories