简体   繁体   English

请求中的Laravel模型关系验证

[英]Laravel model relation validation in request

I find myself doing stuff like this in my controllers whenever I pass in two or more parameters that are related to eachother. 每当我传入彼此相关的两个或多个参数时,我就会发现自己在控制器中执行此类操作。

For example I have this route: 例如,我有这条路线:

Route::patch('user/{user}/post/{post}', 'PostController@update');

Which leads to something like this: 导致这样的事情:

public function update(User $user, Post $post, PostRequest $request)
{
  if($user->id != $post->user_id) {
    // return with error
  }

  // continue
}

Is there a way to put the relation validation in the PostRequest -class? 有没有一种方法可以将关系验证放入PostRequest -class中?

Yes You Could redirect back with error. 是的,您可以重定向回错误。 Try this: 尝试这个:

if($user->id != $post->user_id) {
    return redirect()->back()->with('error', 'Something went wrong.');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM