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 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题