Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@cuonghuynh
Last active November 17, 2023 15:37
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cuonghuynh/48c8a040e344afcab2d8c3a3051612dc to your computer and use it in GitHub Desktop.
Save cuonghuynh/48c8a040e344afcab2d8c3a3051612dc to your computer and use it in GitHub Desktop.
Implement Repository pattern by Eloquent model Laravel
<?php
namespace App\Repositories\Eloquent;
use App\Contracts\Repository\IRepository as InterfaceRepository;
class BaseEloquentRepository implements InterfaceRepository
{
protected $model;
/**
* Class Constructor
* @param $model
*/
public function __construct($model)
{
$this->model = $model;
}
/**
* Get all
* @param array $columns
* @return \Illuminate\Support\Collection
*/
public function all($columns = ["*"])
{
return $this->model->get($columns);
}
/**
* Paginate all
* @param integer $perPage
* @param array $columns
* @return \Illuminate\Pagination\Paginator
*/
public function paginate($perPage = 15, $columns = ['*'])
{
return $this->model->paginate($perPage, $columns);
}
/**
* Create new model
* @param array $data
* @return mixed
*/
public function create($data = [])
{
return $this->model->create($data);
}
/**
* Update model by the given ID
* @param array $data
* @param integer $id
* @return mixed
*/
public function update($data = [], $id, $attribute = 'id')
{
return $this->model->where($attribute, $id)->update($data);
}
/**
* Delete model by the given ID
* @param integer $id
* @return boolean
*/
public function delete($id)
{
return $this->model->destroy($id);
}
/**
* Find model by the given ID
* @param integer $id
* @param array $columns
* @return mixed
*/
public function find($id, $columns = ['*'])
{
return $this->model->find($id, $columns);
}
/**
* Find model by a specific column
* @param string $field
* @param mixed $value
* @param array $columns
* @return mixed
*/
public function findBy($field, $value, $columns = ['*'])
{
return $this->model->where($field, $value)->first($columns);
}
}
@usmansaif
Copy link

Great repository implementation.

@andersonrbernal
Copy link

Great repository implementation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment