Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.
/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;
        }
    }

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

kituneponyo
よわよわぷらぐらま いかに低い意識と技術でその場をどうにかごまかして乗り切るかばかり考えている(乗り切れない)
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away