1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Laravel/Request】Requestクラスでよく使う機能まとめ

Last updated at Posted at 2025-02-06

Laravel の Request クラスは、HTTPリクエストに関する情報(パラメータ、ファイル、ヘッダーなど)にアクセスするための重要なコンポーネントです。
ここでは、コントローラ内で頻繁に利用する Request クラスの機能と使い方を紹介します。


1. リクエストパラメータの取得

a. GET/POST パラメータの取得

  • input()
    フォームやクエリパラメータから値を取得できます。
    例:

    public function store(Request $request)
    {
        // 単一の入力値を取得
        $name = $request->input('name');
        
        // デフォルト値を指定して取得
        $page = $request->input('page', 1);
        
        // 全ての入力値を配列で取得
        $all = $request->all();
        
        // 利用例: $all を元にモデルを作成するなど
    }
    

b. 特定のキーだけを取得

  • only() / except()
    必要なキーだけ、または除外したキーを取得する場合に便利です。

    // name と email のみを取得
    $data = $request->only(['name', 'email']);
    
    // password を除外して取得
    $data = $request->except(['password']);
    

2. クエリパラメータの取得

  • query()
    URLのクエリパラメータ(GETパラメータ)のみを取得したい場合に使用します。

    public function index(Request $request)
    {
        // ?page=2 のようなパラメータを取得
        $page = $request->query('page', 1);
        
        // 全てのクエリパラメータを取得
        $queries = $request->query();
    }
    

3. ルートパラメータの取得

  • route()
    ルート定義で渡されたパラメータにアクセスできます。
    ※ ルートモデルバインディングを利用している場合は、直接コントローラの引数で受け取ることも可能です。

    // ルート: Route::get('/user/{id}', [UserController::class, 'show']);
    public function show(Request $request)
    {
        // ルートパラメータ 'id' を取得
        $userId = $request->route('id');
    }
    

4. ファイルのアップロード

  • file()
    アップロードされたファイルにアクセスします。
    Laravelでは、アップロードファイルは Illuminate\Http\UploadedFile クラスとして扱われます。

    public function upload(Request $request)
    {
        if ($request->hasFile('avatar')) {
            $file = $request->file('avatar');
            
            // ファイルの保存
            $path = $file->store('avatars', 'public');
            
            return back()->with('status', 'アップロード成功');
        }
        
        return back()->withErrors(['avatar' => 'ファイルがアップロードされていません。']);
    }
    

5. ヘッダーの取得

  • header()
    リクエストヘッダーにアクセスできます。
    例:

    public function info(Request $request)
    {
        $userAgent = $request->header('User-Agent');
        return response()->json(['user_agent' => $userAgent]);
    }
    

6. セッションとの連携

  • session()
    リクエストオブジェクトからセッションにアクセスでき、値の取得や設定が可能です。

    public function store(Request $request)
    {
        // セッションに値を保存
        $request->session()->put('key', 'value');
        
        // セッションから値を取得
        $value = $request->session()->get('key', 'default');
        
        // 全てのセッションデータを取得
        $allSessionData = $request->session()->all();
    }
    

7. リクエストメソッドの判定

  • isMethod()method()
    リクエストが GETPOST などのどのメソッドかを確認できます。

    public function process(Request $request)
    {
        if ($request->isMethod('post')) {
            // POSTリクエストの場合の処理
        }
        
        // または
        $method = $request->method();
        if ($method === 'GET') {
            // GETリクエストの場合の処理
        }
    }
    

8. JSON リクエストの取得

  • json()
    JSON形式のリクエストボディから値を取得できます。

    public function apiStore(Request $request)
    {
        // JSONから 'title' を取得
        $title = $request->json('title');
        
        // JSON全体を配列として取得
        $data = $request->json()->all();
    }
    

まとめ

Laravel の Request クラスは、以下のような機能を提供しており、コントローラ内での入力データの取得や操作に欠かせません。

  • 入力値の取得: input(), only(), except()
  • クエリパラメータ: query()
  • ルートパラメータ: route()
  • ファイルアップロード: file()
  • ヘッダー情報: header()
  • セッション連携: session()
  • リクエストメソッドの判定: isMethod(), method()
  • JSONリクエスト: json()

これらの機能をうまく活用することで、より柔軟で使いやすいリクエスト処理を実現できます。
実際のプロジェクトでぜひ役立ててみてください!


参考リンク

以上、Request クラスでよく使う機能のまとめでした。
ご意見・ご質問があればコメントいただけると嬉しいです!

1
1
0

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?