php - Laravel 5.2: ModelNotFoundException for specific models -


i'm new coding in laravel, , i've been following laravel basics videos jeffery way. right i'm working on building own site allow users register, send , receive messages, , post forum.

i'm setting sending/receiving messages , have working enough, want safe-guard against user trying send message invalid username.

the form basic now: 'send_to' takes username, 'title', , 'body'.

my message model has mutator queries database username , sets 'send_to' field user's id.

    public function setsendtoattribute($value)     {         $user = user::where('name', $value)->firstorfail();          $this->attributes['send_to'] = $user->id;     } 

what i'd catch exception if username invalid. i've done handler.php file below:

public function render($request, exception $e) {     if($e instanceof modelnotfoundexception)         return $e->getmessage();     return parent::render($request, $e); } 

so works great , will return message "no query results model [app\user]. i'd prefer though set returns form again title , body filled out, , error message saying username not registered.

one other part this, can done separately modelnotfoundexceptions if i'm trying specific message won't return user not found?

instead of hiding logic inside mutator, can create formrequest or validate user in controller.

using validation rules, can check input user existence, , redirect on failure, or return 422 error in case you're using ajax request (with header accept: application/json)

i'd highly recommend read validation , check specific rule link below:

https://laravel.com/docs/5.2/validation#rule-exists

then, once you're sure user exists in database (remember validate user unique when create it), can write logic insert user id instead of username, if want of course.


Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -