Make Laravel API-only

Tsubasa Kondo
2 min readJul 18, 2019

--

1. Create a Laravel Project

Do “composer create-project”, or do “git clone” an existing Laravel project.

See the following article, if you want to create a Laravel project on Docker.
https://medium.com/@tsubasakondo_36683/create-a-project-for-laravel-282e88ac76fc

See the following article, if you want to create a Laravel project on AWS Cloud9.
https://medium.com/@tsubasakondo_36683/how-to-setup-laravel-on-cloud-9-9cf13cf17699

2. Add middleware to change Response to JSON

$ touch app/Http/Middleware/ForceJson.php// Edit "ForceJson.php" as follows.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class ForceJson
{
/**
* Handle an incoming request.
*/
public function handle(Request $request, Closure $next)
{
$request->headers->set('Accept', 'application/json');
return $next($request);
}
}
// Edit app/Http/Kernel.php
protected $middleware = [
...
\App\Http\Middleware\ForceJson::class
];

3. Install a CORS library

$ composer require spatie/laravel-cors// Edit app/Http/Kernel.php
protected $middleware = [
...
\Spatie\Cors\Cors::class
];
$ php artisan vendor:publish --provider="Spatie\Cors\CorsServiceProvider" --tag="config"// Edit "config/cors.php".

See the following URL for details.
https://github.com/spatie/laravel-cors

4. Confirm Kernel.php

Confirm settings

For example, if “routes/api.php” is the above, the endpoint will be as above.

The error message is displayed in JSON, because “ForceJson Middleware” is added.

--

--

Tsubasa Kondo

I am a Japanese software developer living in Mandalay (Myanmar).