LoginSignup
4
3

More than 5 years have passed since last update.

Laravel5 で URL末尾のIDをチェックしたい

Posted at
/article/edit/123

とか

/article/destroy/456

とか、ログインユーザの閲覧・操作権限チェックしたい

暗黙のコントローラ使ってると基本的に末尾のIDが操作対象やろ

ArticleController.php
class ArticleController extends Controller {

    /**
     * @var 操作対象
     */
    var $article;

    /**
     * Create a new authentication controller instance.
     *
     * @return void
     */
    public function __construct(Request $request)
    {
        parent::__construct();

        // もちろん middleware でやってもええねんけど

        //$this->middleware('article');

        // ['article', 'edit', '123']
        $segments = $request->segments();

        // 123
        $id = array_pop($segments);

        // indeとかcreateとか末尾にIDつかないのもある
        if (is_numeric($id)) {

            $article = Article::find($id);

            if ( ! $article) {
                return response('Unauthorized.', 401);
            }

            if ($article->user_id != $this->me->id) {
                return response('Unauthorized.', 401);
            }

            // あとで再利用するやで
            $this->article = $article;
        }
    }

もっとかっこいい方法あったらおしえてください

4
3
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3