How to show error message on true false value in laravel? - laravel

I am working on a module and want to throw an error message of 401 when the value is false.
I am doing something like this.
if(!$data) {
throw new \ErrorException('Error found');
}
any better way to do this?

You could use one of the helper methods to throw exceptions and display error messages as a response. See here: https://laravel.com/docs/master/helpers#method-abort
The same result could be achieved with abort_unless().
// If data evaluates to false.
abort_unless($data, 401, 'Error found');

Related

Laravel: Where does report() store the error messages?

According to the Laravel handling error documentation I've put this code snippet in one of my functions:
try {
// Send an email...
} catch (Throwable $e) {
report($e);
return false;
}
Now I want to check out the error messages but I have no idea where they are stored.
I've tried both storage/logs/laravel.log and var/log/apache2/error.log but I found nothing.
Where does report() store the error message ?
It depends on your config/logging.php.
By default it should be the stack channel.
If your channel is set up to daily it willl create a file per day (e.g: laravel-2022-05-16.log
Otherwise you can leave the single channel it will put everything in storage/logs/laravel.log

How to Catch a "Trying to get property of non-object Error" in Laravel

How can I find the culprit of the following error in Laravel?
Trying to get property of a non-object Error
This is most probably coming from calling a method\property on a null object. So to fail early, you should use Model::firstOrFail(); or Model::findOrFail(ID);.
Other than that a null check can do it before you use, but it gets ugly if you have many null checks in your code.
try {} catch (\Exception $e) {} is also a way to catch an exception and handle it manually, but doing this in many places is again a lot of work.
What I do is use a ternary operation on the model before accessing properties of that model like so
$model = Model::find($id); $model ? $name = $model->name : null;
with this you can always be rest assured that a fatal throwable error would not be thrown if the model is not found. This also means you have to check if the variable name is not null before working with it like so if(!is_null($name) { //do your stuff here}

Laravel redirect ALL types of errors to custom view

I'm looking for a way to catch all possible errors and redirect all types of errors to 1 page.
My current code in /Exceptions/Handler.php:
if ($this->isHttpException($exception)) {
$statusCode = $exception->getStatusCode();
switch ($statusCode) {
case '404':
return response()->view('layouts/404');
}
}
Problem is that ErrorException (E_NOTICE) types (which are caused by possible bugs in the code) aren't redirected to the 404 page. These errors end up on the 'Woops something went wrong' page.
I basically am trying to make every type of error end up on my custom error page.
All attempts end up on white pages.
What am I not seeing?
Well, to do what you're asking for you should go to App\Exceptions\Handler.php and there, you need to modify the render method:
public function render($request, Exception $exception)
{
abort(404);
}
But I insist, this is a terrible idea, you should catch the Exceptions that your app may get and show the error message to the user in a clean way, for example:
try{
//... your fancy code here
}catch(Exception $e){
// return with the message error $e->getMessage()
}

The HTTP status code "0" is not valid

The HTTP status code "0" is not valid.
public function filter()
{
$institute = (new Institute)->newQuery();
$institute->with(['locations','courses' => function ($query) use ($request){
$query->with('trainers');
}]);
}
$data = $institute->get();
if(count($data) > 0)
{
return response()->json($data);
}
else
{
return response()->json(404,'No Data found');
}
}
Actually, I want to display error 404 message if there is no data,
my problem is when I try to check whether data is there or not I'm getting an error called InvalidArgumentException.Can anyone help on this please.
return response()->json(404,'No Data found');
The first argument of json should be data, then goes a status code. In this case the status code gets 0 value. Simply do it as follows:
return response()->json('No Data found', 404);
This error is thrown when you try and use 0 as your response exception code. In my case my App/Exceptions/Handler.php file was modified and I returned 0 as my HTTP code after formatting which is not allowed. Just make sure you are returning a valid HTTP code from your Exception handler at all times.
Another case can cause the same problem when you have a difference between code and database schema.
In laravel, I had this issue when trying to do an insert on a table where I had the field type incorrect. In my specific case, I was trying to insert a varchar into an integer field in my DB Schema.
Changed the Schema to varchar and I was all set!

Respect\Validation\Validator - using an array while catching errors

I am attempting to catch errors utilizing the Respect\Validation\Validator opensource PHP class. I used their example to create an array of checks. Although that seems to work ok, I then attempted to catch any error messages so that I could display it to the user. I saw no method to do so as a full array (check everything, store all messages in an array). So instead, I tried to cycle through using the check method in Validator.
This is inside of a class method, using the F3 (Fat Free) Framework.
I end up with the following error:
Cannot use object of type Respect\Validation\Validator as array
The code is below. What is the proper way to perform this task using arrays here? Thank you for the assistance!
$registerValidator =
Respect\Validation\Validator::attribute('email', Respect\Validation\Validator::email()->length(1,null)->notEmpty())
->attribute('address', Respect\Validation\Validator::stringType()->length(3,null)->notEmpty())
->attribute('city', Respect\Validation\Validator::alpha()->length(2,60)->notEmpty())
->attribute('state', Respect\Validation\Validator::alpha()->length(2,2)->notEmpty())
->attribute('zip', Respect\Validation\Validator::intType()->length(5,5)->notEmpty());
foreach($this->f3->get('POST') as $key => $value){
try{
$registerValidator[$key]->check($value);
} catch (\InvalidArgumentException $e) {
$errors = $e->getMainMessage();
$this->userMessage($errors, 'warning');
$this->f3->reroute('/register');
}
}
I have also tried to use the assert method as found in their docs, but utilizing the below change, I get a different error at a 500 Server Internal Error, instead of seeing my echo:
try{
$registerValidator->assert($this->f3->get('POST'));
} catch (Respect\Validation\Validator\NestedValidationException $e) {
$errors = $e->getMessages();
echo($errors); // I can't even get here.
foreach($errors as $error){
$this->userMessage($error, 'warning');
}
$this->f3->reroute('/register');
}
With this 500 Error, rather than seeing my Echo, so the page stops loading entirely.
All of the required rules must pass for ...
You cannot really use the Validator class as an array like you're doing on $registerValidator[$key]->check($value). The object in $registerValidator variable contain the chain of rules to validate an input.
In your case I believe the input is the array coming from the POST, so first of all you should use the Key validator instead of Attribute.
However the real reason why you cannot catch the errors is because you have a typo on your catch statement, the class name should be Respect\Validation\Exceptions\NestedValidationException like it's stated in the documentation, not Respect\Validation\Validator\NestedValidationException.

Resources