How can I remove an error message from a MessageBag
?
I've been trying to remove a specific element from the message array that MessageBag
uses without any luck.
I'm getting the same error message twice.
@if($errors->has('undefined'))
<div class="alert alert-warning">
<button type="button" class="close" data-dismiss="alert">×</button>
<h4>Failure.</h4>
{{ $errors->first('undefined') }}
</div>
<?
// $messages = $errors->getMessages();
$messages = $errors->toArray();
unset($messages['undefined']);
?>
@endif
@if($errors->any())
<div class="alert alert-error">
<button type="button" class="close" data-dismiss="alert">×</button>
<h4>Error!</h4>
{{ $errors->first() }}
</div>
@endif
I have done something like this and it seems to work.
<?
$messages = $errors->toArray();
?>
@if(array_key_exists('undefined', $messages))
<?
$message_array = $messages['undefined'];
$message = $message_array[0];
unset($messages['undefined']);
?>
<div class="alert alert-warning">
<button type="button" class="close" data-dismiss="alert">×</button>
<h4>Failure.</h4>
{{ $message }}
</div>
@endif
<?
foreach ($messages as $error => $error_array) {
?>
<div class="alert alert-error">
<button type="button" class="close" data-dismiss="alert">×</button>
<h4>Error!</h4>
{{ $error_array[0] }}
</div>
<?
}
?>
But my question still remains? Why is this happening in first place?
Does it has to do with the Session? I know that the errors
variable it is stored in the Session.
http://laravel.com/api/class-Illuminate.Support.MessageBag.html
Unfortunately, Laravel does not offer methods for removing errors from the MessageBag instance. What you can do is make the 'undefined' error a variable so it's not even in the MessageBag to begin with and just use similar logic to show/hide that.
return View::make('test.view')
->with('undefined', 'Something is undefined')
->withInput($input)->withErrors($validator);
Passing by reference example. You could potentially modify the MessageBag
class to have it pass by reference but it would be hacky.
<?php
class foo
{
public $value = 42;
public function &getValue()
{
return $this->value;
}
}
$obj = new foo;
$myValue = &$obj->getValue(); // $myValue is a reference to $obj->value, which is 42.
$myValue = 2;
echo $obj->getValue(); // prints the new value of $obj->value, i.e. 2.
?>
Notice the &
prepended to both the function name and the call.