On laravel 10 site I made a method which returns true or ItemValidAccess exception in case of invalid data :
/**
* Determine whether logged user have access to complete item
*
* @param \App\Models\Item $item
*
* @return true | ItemValidAccess -
*/
public static function onlyOwnerCanCompleteItem(Item $item): true | ItemValidAccess {
throw_if(
$item->creator_id !== Auth::user()->id,
ItemValidAccess::class,
__('You are not allowed to complete this item')
);
return true;
}
Is it correct way to define ItemValidAccess in method description as there is no return statement when I run throw_if ?
"laravel/framework": "^10.34.2"
Thanks in advance!
If you only validate, it makes no sense to return
trueand nothing else. In those cases just do the validation and if it fails, throw the exception and done, because if it does not fail, of course you would gettrueback (adds no value at all), so your code should be like:There is also one more "issue", if you throw an exception, it is an stardard to have
Exceptionin the name:ItemInvalidAccessExceptionmakes more sense.