'best way to store error messages in Laravel (session or variable)
I'm trying to find out what is the best way to store error messages (due to wrong parameters for e.g).
Assuming I'm declaring the accepted parameters in the Controller, but if any other parameter's given, I want to show a page that simply shows the error message 'that a wrong parameter's given'.
Very easy code Example:
if ($param == 'example') {
// some code
} else {
// accepting no other parameter and should return a page with an error message
// session? variable?
}
return view('index/example');
There are Sessions I can use like:
normal session:
session()->put(...)
Problem: Data is kept if I don't delete it manuallyflash a message to the session:
session()->flash(...)
Problem: It's for the next request, so when I correct the wrong parameter I have to reload two times to make the correct page loadsession for current request:
session()->now(...);
Problem: ??
I can also use a normal variable:
$error = 'message;
return view('index', compact('error'));
Problem: Variable with error message will be kept if not deleted manually
I know that session flash messages are created for this kind of messages, but I don't really want to use it because of the problem I've shortly explained above.
I'd like to know about the (dis-)advantages of each method and also which is the best or maybe if there's a recommended one that's actually working pretty well.
Solution 1:[1]
I recommend this piece of code that I'm using for a project:
/*
* Add an error to Laravel session $errors
* @author Pavel Lint
* @param string $key
* @param string $error_msg
*/
function add_error($error_msg, $key = 'default') {
$errors = Session::get('errors', new ViewErrorBag);
if (! $errors instanceof ViewErrorBag) {
$errors = new ViewErrorBag;
}
$bag = $errors->getBags()['default'] ?? new MessageBag;
$bag->add($key, $error_msg);
Session::flash(
'errors', $errors->put('default', $bag)
);
}
This lets you store errors in the same place where Laravel itself does. You get the benefit of $errors
variable being available in all your blade templates automatically. Then somewhere in your blade this standard piece of code would show the errors:
@if ($errors->any())
<div class="alert alert-danger">
There were some errors with your request.
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
Solution 2:[2]
In my case I was trying to store my validation errors even when proper error response is being sent to users. I manage to solve this even in production as by checking exception class in app/Exceptions/Handler.php
class as
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Throwable $exception
* @return \Symfony\Component\HttpFoundation\Response
*
* @throws \Throwable
*/
public function render($request, Throwable $exception)
{
if ($exception instanceof ValidationException) {
Log::debug($exception->errors(), $exception->getTrace());
}
return parent::render($request, $exception);
}
Note: I am using telescope to observe the log as settings:
/**
* Register any application services.
*
* @return void
*/
public function register()
{
// Telescope::night();
$this->hideSensitiveRequestDetails();
Telescope::filter(function (IncomingEntry $entry) {
if ($this->app->environment('local')) {
return true;
}
return $entry->isReportableException() ||
$entry->isFailedRequest() ||
$entry->isFailedJob() ||
$entry->isScheduledTask() ||
$entry->type === EntryType::LOG ||
$entry->type === EntryType::JOB ||
$entry->type === EntryType::MAIL ||
$entry->type === EntryType::QUERY ||
$entry->hasMonitoredTag();
});
}
Solution 3:[3]
request()->session()->flash('default',
request()->session()->get('default', new ViewErrorBag)->put('errors',
new MessageBag(['Error message.'])
)
);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Pavel Lint |
Solution 2 | Bedram Tamang |
Solution 3 | Tyler2P |