I'm fairly new to coding in Laravel, and I've been following the Laravel Basics videos by Jeffery Way. Right now I'm working on building my own site that will allow users to register, send and receive messages, and post to a forum.
I'm setting up sending/receiving messages and have it working well enough, but what I want to do is safe-guard against a user trying to send a message to an invalid username.
The form is very basic for now: 'send_to' takes a username, 'title', and 'body'.
My Message model has a mutator that queries the database for that username and sets the 'send_to' field to that user's id.
public function setSendToAttribute($value)
{
$user = User::where('name', $value)->firstOrFail();
$this->attributes['send_to'] = $user->id;
}
What I'd like to do is catch an exception if the username is invalid. I've done that with the Handler.php file as below:
public function render($request, Exception $e)
{
if($e instanceof ModelNotFoundException)
return $e->getmessage();
return parent::render($request, $e);
}
So this works great and will will return the message "No query results for model [App\User]. What I'd prefer to do though is set it so it returns to the form again with the title and body filled out, and an error message saying that the username is not registered.
One other part to this, can this be done separately from all ModelNotFoundExceptions so if I'm trying to look up a specific message it won't return that a User was not found?