mercredi 21 mars 2018

Laravel repository pattern query building

I have made repository to get records from database. Everything is working but I want to add orderBy method if there is variable in session:

So far I have this:

<?php

namespace App\Repositories;

use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;

class UserRepository
{
    protected $user;
    private   $columns;

    public function __construct(User $user)
    {
        $this->user    = $user;
        $this->columns = ['id', 'email', 'pwd', 'name', 'addr', 'addr_detail', 'addr_no', 'city', 'zip', 'state', 'phone', 'company_number', 'vat_id', 'tax_id', 'unique_string', 'active', 'banned', 'admin'];
    }

    public function getAll()
    {
        if (Session::has('sort')) 
        {
            $sort = Session::get('sort');
            if (isset($sort["users"]) && !empty($sort["users"]))
                $this->user->orderBy($sort['users']['column'], $sort['users']['type']);
        }

        return $this->user->select($this->columns)->withCount([
            'orders',
            'orders as turnover' => function($query) { $query->select(DB::raw("SUM(price) as turnover")); },
            'orders as profit'   => function($query) { $query->select(DB::raw("SUM(profit) as profit")); },
            ])->get();
    }
}

The condition returns true but the records are not sorted by it. I even tried to put $this->user->orderBy() before return but it wasnt sorded at all. It appears it isnt used at all.

Any help appreciated. Thanks



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2HUBivt
via IFTTT

Aucun commentaire:

Enregistrer un commentaire