Home > Mobile >  Laravel attribute set catch exception
Laravel attribute set catch exception

Time:07-08

This is a method I have on a model:

return Attribute::make(
    set: fn ($value) => CarbonInterval::fromString($value)->spec(),
);

However, if the value is some gibberish this throws Carbon\Exceptions\InvalidIntervalException;

What's the best way to catch the error here and leave the property unchanged?

CodePudding user response:

You can use php try-catch here as:

// Try this 
try {
  return Attribute::make(
    set: fn ($value) => CarbonInterval::fromString($value)->spec(),
  );
}

//catch exception if trying fails
catch(Exception $e) {
  echo 'Message: ' .$e->getMessage();
}

CodePudding user response:

can you try with this.

return Attribute::make(
    set: fn ($value) => $value ? CarbonInterval::fromString($value)->spec() : null,
);

CodePudding user response:

I did it by adding a try-catch block to validate the input in the first place (in a Request Validation) and then pass to the attribute set. Apparently try-catch doesn't work there.

'interval'     => [
                'required',
                function($attribute, $value, $fail) {
                    try {
                        CarbonInterval::fromString($value)->spec();
                    } catch (\Exception $e) {
                        $fail('The interval must follow a valid pattern. E.g. "1 month" or "3 months 19 days"');
                    }
                }
            ],
  • Related