Featured image of post How to Remove the Core Service - Views in Laravel

How to Remove the Core Service - Views in Laravel

Optimizing Your Laravel Application by Removing Unnecessary Services

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:

  1. Add a configuration flag in config/app.php:
'enable_admin' => env('ENABLE_ADMIN', false),
  1. Conditionally load service providers:
'providers' => [
    ...
    config('app.enable_admin') ? Illuminate\View\ViewServiceProvider::class : null,
    ...
],

Key Points

  1. Always check dependencies of third-party packages
  2. Use composer.json’s dont-discover for problematic packages
  3. Verify middleware dependencies
  4. 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.