Appearance
Base Service
A BaseService is a class in Laravel that is used to encapsulate the logic around a component, and they may do more than one thing. The Laravel service is a powerful tool for managing class dependencies and performing dependency injection.
A BaseService is basically just a class that handles one thing (single responsibility), so that the functionality that the class provides, can be reused in multiple other parts of the application.
By using a BaseController, developers can reduce the amount of code duplication and make it easier to maintain their application. Additionally, it can help enforce best practices and improve code organization by centralizing common functionality.
In our application, we have created a BaseService named Service inside app/Http/Services folder where different function can be defined which can be extended by other services.
Some functions
This method inject model into the class via the constructor.
protected $model;
public function __construct($model)
{
$this->model = $model;
}
getAllData
In this method query is performed in the model to retrieve the overall data of the table. Here, this->query specifies the model passed in the super function.
public function getAllData($data, $selectedColumns = [], $pagination = true)
{
$query = $this->query();
if (count($selectedColumns) > 0) {
$query->select($selectedColumns);
}
if (isset($data->keyword) && $data->keyword !== null) {
$query->where('name', 'LIKE', '%'.$data->keyword.'%');
}
if ($pagination) {
return $query->orderBy('id', 'DESC')->paginate(Config::get('constants.PAGINATION'));
} else {
return $query->orderBy('id', 'DESC')->get();
}
}
store
The store method is used to save single record in the database.
public function store($request)
{
return $this->model->create($request->except('_token'));
}
storeBulk
The storeBulk method is used to store bulk records in the database.
public function storeBulk($data)
{
return $this->model->createMany($data);
}
update
This method is used to update details of an existing resource.
public function update($request, $id)
{
$data = $request->except('_token');
$update = $this->itemByIdentifier($id);
$update->fill($data)->save();
$update = $this->itemByIdentifier($id);
return $update;
}
delete
This method is used to delete the selected record from database.
public function delete($request, $id)
{
$item = $this->itemByIdentifier($id);
return $item->delete();
}