0
0

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 5 years have passed since last update.

Laravel の Controller を Web と API で使いまわす

Posted at

ベタに。サーバーサイドレンダリングで返す View と、axios で、API呼び出ししたいのと、ほとんど、Controller が同じだったので、api のときは、JSONを、web のときは View を返したかったのだけど、isApi() てきなメソッドがみつからなかったから、つくってみた。

※ もし、違うオフィシャルな実装があれば、教えてやってくださいませ。

基底クラスのコントローラーに isApi() を実装。

"api" ってパス名は、Laravel は、とりあえず定数化とかされていないから、ベタで。

/app/Http/Controllers/Controller.php
<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    function isApi()
    {
        $paths = explode("/", request()->path());
        return $paths[0] == "api";
    }
}

利用するコントローラーでは、こんなかんじで、戻り値を切り替える。

/app/Http/Controllers/HogeController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;

class HogeController extends Controller
{
    public function index()
    {
        // データを取得するなどの処理
        $hoges =  [];

        if ($this->isApi()) {
            return $hoges;
        } else {
            return view('hoge.index', ['hoges' => $hoges]);
        }
    }
}

0
0
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?