Skip to content

Instantly share code, notes, and snippets.

@kennedy-osaze
Created June 7, 2020 09:50
Show Gist options
  • Save kennedy-osaze/9ec02e2ef5c7c758fbdd177333ef943b to your computer and use it in GitHub Desktop.
Save kennedy-osaze/9ec02e2ef5c7c758fbdd177333ef943b to your computer and use it in GitHub Desktop.
Simple Repository in Laravel
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
//
}
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Repository\ProductRepository;
class ProductController extends Controller
{
protected ProductRepository $products;
public function __construct(ProductRepository $products)
{
$this->products = $products;
}
public function show(string $name)
{
dd($this->products->where($name)->first(), $this->products->findByName($name));
}
}
<?php
namespace App\Repository;
use App\Product;
class ProductRepository extends Repository
{
protected string $model = Product::class;
public function findByName(string $name): ?Product
{
return $this->where($name)->first();
}
}
<?php
namespace App\Repository;
abstract class Repository
{
protected string $model;
public function __call($name, $arguments)
{
return app(static::$model)->{$name}(...$arguments);
}
public function __callStatic($name, $arguments)
{
return app(static::class)->{$name}(...$arguments);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment