Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

pekkagaiser's avatar

Most Laravel-y way to be verbose about errors happening inside a model?

Suppose I have a model Rebates that has a calculatePrice($price, $duration) method that adjusts a price for a booking based on the rebate data it contains.

Sometimes, there can be faulty incoming data that cannot be validated/filtered out previously (say, the rebate doesn't apply to this combination of price and duration).

In other contexts, one might return false in this case and perhaps have a lastError property in the model for debugging. Depending on the context (in a web app; in an API call; in a CLI call), this error message would then be passed on by the caller to the correct channel.

Is there a Laravel-y way to do this?

Creating a custom exception type for each kind of error seems a lot of effort. Is this what people do? Or is there a more elegant way?

0 likes
2 replies
LaryAI's avatar
Level 58

One possible solution to handle faulty input inside a model in Laravel is to use Laravel's validation feature. You can define validation rules for the input data and handle any validation errors that occur.

Here's an example of how you can implement this in your Rebates model:

use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;

class Rebates extends Model
{
    public function calculatePrice($price, $duration)
    {
        $validator = Validator::make([
            'price' => $price,
            'duration' => $duration,
        ], [
            'price' => 'required|numeric',
            'duration' => 'required|numeric',
        ]);

        if ($validator->fails()) {
            throw new ValidationException($validator);
        }

        // Perform your calculations here

        return $adjustedPrice;
    }
}

In this example, we use the Validator facade to create a validator instance. We define the validation rules for the price and duration inputs. If the validation fails, we throw a ValidationException which can be caught and handled appropriately.

By using Laravel's validation feature, you can easily handle faulty input and provide meaningful error messages to the user. Additionally, you can customize the validation rules to fit your specific requirements.

Remember to import the necessary classes (Validator and ValidationException) at the top of your file.

Snapey's avatar

You can throw a general exception. No need to create one specifically for this if you don't need to.

1 like

Please or to participate in this conversation.