Skip to content

Instantly share code, notes, and snippets.

@warrenca
Created December 10, 2018 00:28
Show Gist options
  • Save warrenca/5ece4c42089b5b12b4d9cd0cdbddce16 to your computer and use it in GitHub Desktop.
Save warrenca/5ece4c42089b5b12b4d9cd0cdbddce16 to your computer and use it in GitHub Desktop.
Laravel Repository Pattern
<?php
namespace App\Http\Controllers;
use Warrenca\Laravel\Repositories\UserRepository;
/**
* Class CompanyUserController
*/
class CompanyUserController extends Controller
{
public function index($companyId)
{
$userRepository = new UserRepository(new User);
$users = $userRepository->getActiveUserByCompany($companyId);
return view('user.listings', compact('users'));
}
}
<?php
namespace Warrenca\Laravel\Repositories;
use Illuminate\Database\Eloquent\Model;
/**
* Interface ModelServiceInterface
*/
interface ModelRepositoryInterface
{
public function setModel(Model $model);
public function getModel();
}
<?php
namespace Warrenca\Laravel\Services;
use Illuminate\Database\Eloquent\Model;
/**
* Trait EntityServiceTraits
*/
trait ModelRepositoryTraits
{
/**
* @param Model $model
* @return Model
*/
public function setModel(Model $model)
{
abort_unless($this->modelClass === get_class($model), 500);
$this->model = $model;
return $this;
}
/**
* @return Model
*/
public function getModel()
{
return $this->model;
}
}
<?php
namespace Warrenca\Laravel\Repositories;
use Warrenca\Laravel\Models\User;
/**
* Class User
*/
class UserRepository extends Model implements ModelRepositoryInterface
{
protected $modelClass = User::class;
use ModelRepositoryTraits;
public function __construct(User $user = null)
{
$this->model = $user;
}
public function getActiveUserByCompany($companyId)
{
return $this-model->whereIsActive(1)->whereCompanyId($companyId)->get();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment