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 学不会递归,理解不了汉诺塔参数变化
  • ¥30 软件自定义无线电该怎样使用
  • ¥15 R语言mediation包做中介分析,直接效应和间接效应都很小,为什么?
  • ¥15 Jenkins+k8s部署slave节点offline
  • ¥15 如何实现从tello无人机上获取实时传输的视频流,然后将获取的视频通过yolov5进行检测
  • ¥15 WPF使用Canvas绘制矢量图问题
  • ¥15 用三极管设计一个单管共射放大电路
  • ¥15 孟德尔随机化r语言运行问题
  • ¥15 pyinstaller编译的时候出现No module named 'imp'
  • ¥15 nirs_kit中打码怎么看(打码文件是csv格式)