Laravel repository pattern add query

✔ Recommended Answer

I didn't manage to do quite what I wanted, but the fix that was satisfying solution was to put the complete logic inside the method, so now I have this:

public function eagerWhereLike($column, $value, $relation, $searchOnRelation = false, $orderBy = 'name'){    $regions = Region::with($relation)->where($column, 'LIKE', '%' . $value . '%')->orderBy($orderBy);    if ($searchOnRelation) {        $regions->orWhereHas($relation, function ($query) use ($column, $value) {            $query->where($column, 'LIKE', '%' . $value . '%');        });    }    return $regions;}


Answered By: Norgul

Method #2

In Laravel, the repository pattern is a common design pattern used to separate the application logic from the underlying data storage mechanism. The repository pattern provides a layer of abstraction between the application and the data storage, which makes it easier to maintain and test the application.

To add a new query to a repository, you can follow these steps:

  1. Define an interface that declares the methods for the repository. For example:
interface UserRepositoryInterface { public function findById($id); public function findByEmail($email); public function createUser($data); public function searchUsers($searchTerm); // add your new method here }
  1. Create a concrete implementation of the repository interface that contains the logic for the repository methods. For example:
class UserRepository implements UserRepositoryInterface { public function findById($id) { // logic to find a user by id } public function findByEmail($email) { // logic to find a user by email } public function createUser($data) { // logic to create a new user } public function searchUsers($searchTerm) { // logic to search for users } // Implement your new method here public function findByStatus($status) { return User::where('status', $status)->get(); } }
  1. Inject the repository into your controller or service using dependency injection. For example:
class UserController extends Controller { protected $userRepository; public function __construct(UserRepositoryInterface $userRepository) { $this->userRepository = $userRepository; } public function index() { $users = $this->userRepository->findAll(); return view('users.index', compact('users')); } // ... }
  1. Call the new method on the repository from your controller or service:
$activeUsers = $this->userRepository->findByStatus('active');

That's it! You have now added a new query method to your repository using the repository pattern in Laravel.


Most Popular

PhpStorm, return value is expected to be 'A', 'object' returned

Remove Unicode Zero Width Space PHP

Laravel file upload returns forbidden 403, file permission is 700 not 755