Knowledge Base

Empty filter

Laravel create Service

1.create service class in app/Services/ExampleService.php
<?php

namespace App\Services;

class ExampleService
{
public function performAction()
{
// Service logic here
return 'Action performed';
}
}

2.Register in a service provider in app/Providers/AppServiceProvider.php

<?php

namespace App\Providers;

use App\Services\ExampleService;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
$this->app->singleton(ExampleService::class, function ($app) {
return new ExampleService();
});
}

// ...
}

3. use your service through dependency injection in controllers, commands, or other classes:
app/Http/Controllers/ExampleController.php

<?php

namespace App\Http\Controllers;

use App\Services\ExampleService;

class ExampleController extends Controller
{
public function index(ExampleService $service)
{
$result = $service->performAction();

return response()->json(['result' => $result]);
}
}

Published
Back to Index