Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if any error message exists and show all of them in laravel

In laravel for showing all error messages at once i use the following code in the view

<?php 
 $something = $errors->all(); 
 if(!empty($something)): 
?>

<div class = "alert alert-error">                      
  @foreach ($errors->all('<p>:message</p>') as $input_error)
    {{ $input_error }}
  @endforeach 
</div> 

<?php endif; ?>

But when I want to use $errors->all() instead of $something in the if condition it's showing an error

Can't use method return value in write context

Although the above code works fine, I think there may be a better ways to check if any error message exists and if it does then display it.

like image 739
Suman Ghosh Avatar asked Sep 14 '12 07:09

Suman Ghosh


People also ask

How show all errors in Laravel?

How to make Laravel show PHP errors. By default, the Laravel framework has an error handling feature. The debug option in the configuration file determines the error display at the user end. Usually, the Laravel configuration file that enables debugging is the config/app.


2 Answers

Yes, because you can't use any method as empty function parameter. From php docs:

empty() only checks variables as anything else will result in a parse error. In other words, the following will not work: empty(trim($name)). Instead, use trim($name) == false.

What class is $errors? If it's your own class you can implement such method like 'isEmpty()' and then use in if statement:

if ($errors->isEmpty()) { ...
like image 145
Cyprian Avatar answered Oct 17 '22 06:10

Cyprian


In my controller I use the following code to pass validation errors to my view:

return Redirect::to('page')
    ->withErrors($validator);

Then, in my view, I can use the following code to check if errors exist:

@if($errors->any())
<div id="error-box">
    <!-- Display errors here -->
</div>
@endif

You can also use if($errors->all()).

From the Laravel (v4) docs:

Note that when validation fails, we pass the Validator instance to the Redirect using the withErrors method. This method will flash the error messages to the session so that they are available on the next request... [A]n $errors variable will always be available in all of your views, on every request, allowing you to conveniently assume the $errors variable is always defined and can be safely used.

like image 32
chipit24 Avatar answered Oct 17 '22 05:10

chipit24