App\Data\Repositories\Repository::getByAttributes PHP Method

getByAttributes() public method

Two operators values are handled: AND | OR.
public getByAttributes ( array $attributes, string $operator = 'AND', array $relations = null ) : Collection
$attributes array
$operator string
$relations array
return Illuminate\Support\Collection
    public function getByAttributes(array $attributes, $operator = 'AND', $relations = null)
    {
        // In the following it doesn't matter wivh element to start with, in all cases all attributes will be appended to the
        // builder.
        // Get the last value of the associative array
        $lastValue = end($attributes);
        // Get the last key of the associative array
        $lastKey = key($attributes);
        // Builder
        $query = $this->model->where($lastKey, $lastValue);
        // Pop the last key value pair of the associative array now that it has been added to Builder already
        array_pop($attributes);
        $method = 'where';
        if (strtoupper($operator) === 'OR') {
            $method = 'orWhere';
        }
        foreach ($attributes as $key => $value) {
            $query->{$method}($key, $value);
        }
        if ($relations && is_array($relations)) {
            foreach ($relations as $relation) {
                $query->with($relation);
            }
        }
        return $query->get();
    }