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?

More than 1 year has passed since last update.

laravelでwithの中のwhereでRequestを使う方法

Last updated at Posted at 2022-12-29

環境

  • php:8.1
  • laravel:9.23.0

対象

  • laravelでwithを使っていてその中でRequestの値を条件として使いたい人

前提

  • usersテーブルはcompaniesテーブルとリレーションされている状態

方法

  • ダメなパターン
    これだとRequestが使えない状態になっています
UserController.php
<?php

declare(strict_types=1);

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function getSearchUsers(Request $request)
    {
        $query = User::query()->with(['company'])->whereHas('company', function ($query) {
            $company_id = $request->query('company_id');            
            $query->where('companies.company_id', '=', $company_id);
        });
        return $query->get();
    }
}

  • OKなパターン
    変更点は function ($query) use ($request) { の所です
UserController.php
<?php

declare(strict_types=1);

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function getSearchUsers(Request $request)
    {
        $query = User::query()->with(['company'])->whereHas('company', function ($query) use ($request) {
            $company_id = $request->query('company_id');            
            $query->where('companies.company_id', '=', $company_id);
        });
        return $query->get();
    }
}

まとめ

useを使用することで親スコープの変数を使うことができる

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?