LoginSignup
5
1

More than 5 years have passed since last update.

Laravel5.6 で URL からコントローラのアクションを逆引きする

Posted at

やりたいこと

routes/web.php
Route::get('hoge', 'HogeController@index');
Route::get('fuga', 'FugaController@index');

みたいになっているときに https://xxx.com/hoge という情報から HogeController@index を得たい。

確認環境

  • Laravel 5.6
  • PHP 7.1

コード

Route::getRoutes() でiterable なルーティング一覧 Illuminate\Routing\RouteCollection を返してくれるようなので、それを使う。

function uriToAction($uri, $method = 'GET')
{
    $route = collect(Route::getRoutes())
        ->where('uri', $uri)
        ->filter(function ($route) use ($method)  {
            return in_array(strtoupper($method), $route->methods);
        })
        ->first();

    return $route->action['uses'] ?? null;
}
実行結果
>>> uriToAction('hoge');
=> "App\Http\Controllers\HogeController@index"

あとはお好みで parse_url() などを使ってフルの URL から解決できるようにしたり、App\Http\Controllers\ を削ったりとか。

このコードではルーティングパラメータに対応してないが、それも頑張ればできそう。

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