Author - StudySection Post Views - 738 views
Service Layer in Laravel

How to use the Service Layer in Laravel

Every developer tries to maintain their code properly. They want to make their code more reusable and keep it clean. This can only be possible when they divide their code into different layers. The service layer in Laravel is the critical layer for making your business logic reusable.

As we know, controllers should only handle input. We usually keep logic in the models, but after some time, they get “fat”. At this point, we can take advantage of the service layer in Laravel.

What can we do in this layer:

  1. Implement Validation Checks
  2. Handle CRUDS
  3. Make customization in the result returned by Model
  4. Send Mails

When you want to create a service class in Laravel, just go to the app/services folder. Then create a class like I am creating a user class in the image below:
<?php
namespace App\Services;
use Validator;
use Mail;
use App\Models\User as UserModel;
class User
{
/** Get a validator for a user. *********/
public function validator(array $data)
{
return Validator::make($data, [
'email' => 'required|email|max:255',
'phone' => 'max:255',
'first_name' => 'required|max:255',
'last_name' => 'required|max:255'
]);
}
/** Create a new user instance after a valid form. */
public function create(array $data)
{
$data = [
'email' => $data['email'],
'firstName' => $data['firstName'],
'lastName' => $data['lastName'],
'language' => $data['language'],
'phone' => $data['phone'],
'message' => $data['message'] ];
// You can also write the email code here to send it to the newly created User
return UserModel::create($data);
}
}

This is my Controller where I am calling my Service Class in the user() method:

<?php
namespace App\Http\Controllers;
use App\Services\User as UserService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Lang;
class UsersController extends Controller
{
public function __construct(Request $request)
{
$this->_request = $request;
}
public function user(UserService $userService)
{
$errors = null;
$success = false;
if ($this->_request->isMethod('post')) {
$validator = $userService->validator($this->_request->all());
if ($validator->fails()) {
$errors = $validator->errors();// Returns errors
} else {
$userService->create($validator->getData());
$success = true;
}
}
return view('pages/user, ['errors' => $errors, 'success' => $success]); // Redirect to the User view page
}
}

If you have knowledge of financial accounting and you are in search of a good job, financial accounting certification can help you reach your desired goals. StudySection provides Financial accounting certification for beginner level as well as expert level people in the commerce stream. You can appear in the certification exam for free to get certified.

Leave a Reply

Your email address will not be published.