Search code examples
phpvalidationlaravel

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.


Solution

  • 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()) { ...