PHP code example of phucnguyenvn / laravel-eloquent-repository

1. Go to this page and download the library: Download phucnguyenvn/laravel-eloquent-repository library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

phucnguyenvn / laravel-eloquent-repository example snippets


'providers' => [
    ...
    phucnguyenvn\EloquentRepository\Providers\RepositoryServiceProvider::class,
],

namespace App\Repositories;

use App\Models\User;
use phucnguyenvn\EloquentRepository\Repositories\EloquentRepository;

class UserRepository extends EloquentRepository
{
    /**
     * Repository constructor.
     */
    public function __construct(User $user){
        parent::__construct($user);
    }
}

namespace App\Repositories;

use App\Models\User;
use phucnguyenvn\EloquentRepository\Repositories\EloquentRepository;

class UserRepository extends EloquentRepository
{
    /**
     * Repository constructor.
     */
    public function __construct(User $user){
        parent::__construct($user);
    }
    
    public function getAllUser(){
        return $this->all();
    }
    
    public function getByName($name) {
        return $this->where("name", $name)->get();
    }
    
    // You can create methods with partial queries
    public function filterByProfile($profile) {
        return $this->where("profile", $profile);
    }
    
    // Them you can use the partial queries into your repositories
    public function getAdmins() {
        return $this->filterByProfile("admin")->get();
    }
    public function getEditors() {
        return $this->filterByProfile("editor")->get();
    }
    
    // You can also use Eager Loading in queries
    public function getWithPosts() {
        return $this->with("posts")->get();
    }
}

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Repositories\UserRepository;

class UserController extends Controller
{
    protected function index(UserRepository $repository) {
        return $repository->getAdmins();
    }
}

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Repositories\UserRepository;
class UserController extends Controller
{
    private $userRepository;
	public function __construct()(UserRepository $userRepository) {
        $this->userRepository = $userRepository;
    }
    
    public function index() {
        return $this->userRepository->getAllUsers();
    }
    
}