- Previous article: Speed Up Your Service Performance by Reducing Service Provider Boot Time 2.0
- A reader mentioned errors when directly removing the View service. This article demonstrates how to properly remove the View service.
Step-by-Step Guide
1. Create a New Laravel Project
composer create-project laravel/laravel=7.* laravel-demo
2. Modify the Default Route
Edit routes/web.php
to return JSON instead of a view:
Route::get('/', function () {
return [
'code' => 200,
'msg' => 'hello'
];
});
3. Disable the View Service Provider
Comment out the View service provider in config/app.php
:
// 'providers' => [
// ...
// Illuminate\View\ViewServiceProvider::class,
// ...
// ],
4. Handle Ignition Package Dependency
Add to composer.json
to prevent automatic registration:
"extra": {
"laravel": {
"dont-discover": [
"facade/ignition"
]
}
},
Then run:
composer dump-autoload
5. Fix Middleware Dependency
Comment out the view-related middleware in app/Http/Kernel.php
:
// \App\Http\Middleware\ShareErrorsFromSession::class,
6. Custom Error Handling
Modify app/Exceptions/Handler.php
to handle errors without views:
public function render($request, Throwable $exception)
{
$code = 500;
if ($exception instanceof NotFoundHttpException) {
$code = 404;
}
return (new Response(json_encode([
'code' => $code,
'msg' => $exception->getMessage()
])))->withHeaders(['Content-Type' => 'application/json']);
}
Handling Mixed Environments (API + Admin)
For projects using both API and admin panels:
- Add a configuration flag in
config/app.php
:
'enable_admin' => env('ENABLE_ADMIN', false),
- Conditionally load service providers:
'providers' => [
...
config('app.enable_admin') ? Illuminate\View\ViewServiceProvider::class : null,
...
],
Key Points
- Always check dependencies of third-party packages
- Use
composer.json
’sdont-discover
for problematic packages - Verify middleware dependencies
- Implement custom error handling for API-only responses
By following these steps, you can safely remove the View service while maintaining API functionality. The final application will return JSON responses without any view-related components, reducing memory usage and improving performance.