🤖

Laravelでストアドを実行する

2023/07/18に公開

DB ファサードのselectを利用する

use Illuminate\Support\Facades\DB;

// ストアドを実行する
$params['user_id'] = 1;
$user = DB::select("CALL getUser(:user_id, $params);
return $user;

リポジトリ層を作る

namespace App\Repositories;

use Illuminate\Support\Facades\DB;

class UserRepository
{
    public function getUser($userId)
    {
        $params = [
            'user_id' => $userId
        ];

        $user = DB::select("CALL getUser(:user_id)", $params);
        return $user;
    }
}

リポジトリを使う

namespace App\Http\Controllers;

use App\Repositories\UserRepository;

class UserController extends Controller
{
    protected $userRepository;

    public function __construct(UserRepository $userRepository)
    {
        $this->userRepository = $userRepository;
    }

    public function getUser($userId)
    {
        $user = $this->userRepository->getUser($userId);
        return $user;
    }
}

Discussion