简体   繁体   中英

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?

Yes You Could redirect back with error. Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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