How to Use Service Class In Laravel?

In this tutorial, I will give you an example of “How to Use Service Class In Laravel”, So you can easily apply it with your laravel 7, laravel 8, and laravel 9, application.

First, what we’re doing here, This is the example :

service class in laravel
get records using service class in laravel

Service Class In Laravel

A service class is a class that performs some business logic that you want to use in various places. It is any Laravel object that performs some sort of a “global” task.

How/where do We create service classes in Laravel :

When code does not naturally fit into one class or another nicely then you have a candidate for a service. For example, there may be a post service. These are posts that need to be repeated over and over again in different places.

Generating Migration with Model :

php artisan make:model Post -m

Migration Structure :

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->Text('content');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
};

Run Migration :

php artisan migrate
post table migration

app\Models\Post.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;
}

Insert some Dummy Post Records :

post table with records

Create a folder for Service Class :

app\Services

create a service class in laravel

Now you can create multiple services for a class, you can put all the required code like view, edit, and image upload in the service class, using the service class you can clean and reusable code in your controller in the entire Laravel application.

Related article:- How to use Traits in Laravel 8.

app\Services\PostService.php

<?php

namespace App\Services;
use App\Models\Post;

class PostService
{

	public function getAllPost(){
		return Post::get();
	}

	public function getPost($id){
		return Post::whereId($id)->first();
	}
}

Create a Controller :

php artisan make:controller PostController

routes\web.php :

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;


/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/posts',[PostController::class,'index']);
Route::get('/post-view/{id}',[PostController::class,'show']);

Define services into the constructor and inject them into the class

app\Http\Controllers\PostController.php :

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Services\PostService;

class PostController extends Controller
{
    protected $postservice;

    public function __construct(PostService $postservice)
    {
        $this->postservice = $postservice;
    }

    public function index()
    {
        $posts = $this->postservice->getAllPost();
       
        return view('post.index',['posts'=>$posts]);

    }

    public function show($id)
    {
        $post = $this->postservice->getPost($id);
       
        dd($post);
    }
}

Run Application :

http://127.0.0.1:8000/posts
get records using service class in laravel
http://127.0.0.1:8000/post-view/2
show records id using service class in laravel

In this article, we learned “How to create and use Service Class In Laravel”, I hope this article will help you with your Laravel application Project.

Read also:- XSS (Cross-Site Scripting) Protection In Laravel.

Hi, My name is Gaurav Pandey. I'm a Laravel developer, owner of 8Bityard. I live in Uttarakhand - India and I love to write tutorials and tips that can help other developers. I am a big fan of PHP, Javascript, JQuery, Laravel, WordPress. connect@8bityard.com