PHP code example of forecho / laravel-repository

1. Go to this page and download the library: Download forecho/laravel-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/ */

    

forecho / laravel-repository example snippets


 
namespace App\Repositories;

use App\Models\Post;
use Forecho\LaravelRepository\Repository;

class PostRepository extends Repository
{
    // Optional
    public array $partialMatchAttributes = ['title'];

    // Optional
    public array $defaultOrder = ['created_at' => 'desc'];
    
    // Optional
    public array $booleanAttributes = ['status'];

    public string $modelClass = Post::class;

    // Optional
    public function boot()
    {
        $this->pushCriteria(UserCriteriaCriteria::class);
    }

}


namespace App\Http\Controllers;

use App\Repositories\PostRepository;
use Illuminate\Http\Request;
use App\Http\Resources\UserResource;

class UserController extends Controller
{
    protected PostRepository $repository;

    public function __construct(PostRepository $accountRepository)
    {
        $this->repository = $accountRepository;
    }
   
    public function index(Request $request, PostRepository $userRepository)
    {
        $posts = $this->repository->search($request->all())->paginate();
        // $posts = $this->repository->with(['user'])->search($request->all())->paginate();
        
        return response()->json(UserResource::collection($posts);
    }
}


namespace App\Criteria;

use App\Services\UserService;
use Forecho\LaravelRepository\Contracts\CriteriaInterface;
use Forecho\LaravelRepository\Contracts\RepositoryInterface;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

class UserCriteriaCriteria implements CriteriaInterface
{
    /**
     * Apply criteria in query repository
     *
     * @param  Builder|Model  $model
     * @param  RepositoryInterface  $repository
     * @return mixed
     */
    public function apply($model, RepositoryInterface $repository): mixed
    {
        return $model->where('user_id', UserService::getUserId());
    }
}