8
10

More than 5 years have passed since last update.

Laravel5 で毎回毎回 \Auth::user() とか $request::all() とかするのめんどくさい

Posted at
ArticleController.php
public function postStore (Request $request)
{
    // とてもめんどくさい
    $data = $request->all();
    // あるいは Input::all();

    // とてもめんどくさい
    $user = \Auth::user();

    Article::create([
        'title' => $data['title'],
        'body' => $data['body'],
        'user_id' => $user->id
    ]);
}
LazyController.php
class LazyController extends Controller {

    var $me;

    var $input;

    public function __construct()
    {
        $this->middleware('auth');

        $this->me = \Auth::user();

        $this->input = Input::all();
    }
} 
ArticleController.php
class ArticleController extends LazyController {

    public function __construct () {
        parent::__construct();

        // ここに書いてもいいけど
        // それはそれでコントローラごとにかかなあかんからめんどくさい
    }

    public function postStore (Request $request)
    {
        // らくちん
        Article::create([
            'title' => $this->input->['title'],
            'body' => $this->input->['body'],
            'user_id' => $this->me->id
        ]);
    }
}

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

8
10
3

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
8
10