dquv73115 2016-01-27 22:21
浏览 577
已采纳

Laravel 5.2:特定模型的ModelNotFoundException

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?

  • 写回答

1条回答 默认 最新

  • dongyi8416 2016-01-28 00:27
    关注

    Instead of hiding the logic inside a mutator, you can create a FormRequest or validate the user in your controller.

    Using validation rules, you can check the input for user existence, and redirect back on failure, or return a 422 error in case that you're using an ajax request (with the header Accept: application/json)

    I'd highly recommend you to read about validation and check this specific rule I link below:

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

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?