1

Details

I want to

  • Count all my distributors that I query
  • Send it along within the JSON file
  • I know that I have 89 distributors in total, I did this dd(count($distributors));

  • I am sure what is the best practice for this.

Here is what I have tried

  • I initialize $count = 0;
  • Increment by 1 every time the loop execute $count = $count + 1;
  • Send the result toArray 'count' => $count->toArray() as part of my distributors array

Here is my code

public function index()
{
    $distributors = [];
    $count = 0;

    foreach( 

        // Specific Distributors 
        Distributor::where('type','!=','OEM')->where('type','!=','MKP')
        ->get() as $distributor){

        // Variables
        $count = $count + 1; 
        $user = $distributor->user()->first();

        $distributors[$distributor->id] = [

        'user' => $user->toArray(),
        'distributor' => $distributor->toArray(),
        'hq_country' => $distributor->country()->first(),
        'address' => $distributor->addresses()
        ->where('type','=','Hq')->first()->toArray(),

        'count' => $count->toArray()

        ];
    }

    return Response::json($distributors);
}

Result

The code won't run, due to my $distributor array is not exist ...

It will run, if I take 'count' => $count->toArray() off .

Updated

  • I am using Laravel 4.0
  • The code is part of my UrlController.php
iori
  • 3,236
  • 12
  • 43
  • 78
  • 1
    `$count = 0;`, `$count = $count + 1;`, then you try to use `$count->toArray()`? You're treating an integer like an object. – sjagr Jan 09 '15 at 15:17
  • @sjagr : what do you suggest in order to fix this ? can you help me please – iori Jan 09 '15 at 15:18
  • 1
    Could you not just do `'count' => $count`? Not sure why you're trying to make `count` an array when it's just going to be a number. Or (if you really want it as an array) `'count => array('count' => $count)`, but that seems quite redundant to me. – Tim Lewis Jan 09 '15 at 15:20
  • 1
    I don't know. I didn't write this code. It depends on what you want `count` to mean to you. If you're using the aggregate count, use `'count' => $count` on its own. If you're trying to get the count of the query, use `'count' => count($distributors)` like you said yourself. – sjagr Jan 09 '15 at 15:32
  • 2
    I don't know but I have a hard time imagining why you would want to send a count of all items in your result with your result. Can't you just count them when you receive the response? e.g. in javascript: `data.length` – lukasgeiter Jan 09 '15 at 15:33
  • @lukasgeiter : I'm trying to work my way around it. I am not even sure that my approach is the best solution, but your suggestion seem elegant, and short, do you mind answer it. How do I count it after receive the response ? I hope you don't mind helping me. I'll make sure to accept it. – iori Jan 09 '15 at 16:10

3 Answers3

1

It really doesn't make a lot of sense to add this kind of count to your result. It is much simpler to just send the result and let the client do the counting. Because the information on how much distributors you actually have is right in your array of distributors. It's just it's length.

Here's an example with javascript (and $.ajax although that doesn't really matter)

$.ajax({
    url: 'get/distributors',
    method: 'GET'
}).done(function(data){
    var count = data.length;
});
lukasgeiter
  • 147,337
  • 26
  • 332
  • 270
  • Well answer ! Do you mind update your answer, and show how to get the same result but in php instead ? I am trying to view that count. - If you don't mind. :) – iori Jan 09 '15 at 16:26
  • What do you mean? The `.length` of php is `count()`. Or maybe I don't understand your question correctly... – lukasgeiter Jan 09 '15 at 16:30
1

Model:

class Distributor extends Eloquent {
    public function country()
    {
        return $this->hasOne('Country');
    }

    public function addresses()
    {
        return $this->hasMany('Address');
    }

    public function hqAddress()
    {
        return $this->addresses()->where('type', 'Hq')->first();
    }

    public function user()
    {
        return $this->hasOne('User');
    }
}

Controller:

$distributors = Distributor::whereNotIn('type', ['OEM', 'MKP'])
    ->with('country', 'user')->get();

$count = 0;
$distributors->each(function(Distributor $distributor) use(&$count) {
    $distributor->count = $count;
    $count++;
});

return Response::json($distributors);
Laravelian
  • 558
  • 1
  • 3
  • 10
0

Sorry, I can be wrong.

I am not laravel expert.

But what is this fragment is about?

this Index function is part of Model?

@evoque2015 is trying to put some custom array into $distributors[$distributor->id]?

if that is the goal, could you do any test with any simple value of 'count' that sholud work in your opinion?

My guess is : 'count' index is not acceptable for your Distributor::where function

(if it is acceptable - show as the value of 'count' that doesn't break your code even if return wrong result/data ).

So I would try to change the name of this parameter either to 'my_custom_count', should it be declared somewhere in Distributor model declaration?

Found this : Add a custom attribute to a Laravel / Eloquent model on load?

It seems to prove my guess.

So we need to change model class like:

class Distributor extends Eloquent {

    protected $table = 'distributors';//or any you have already

    public function toArray()
    {
        $array = parent::toArray();
        $array['count'] = $this->count;
        return $array;
    }

.....
}

and probably more changes in model or just add 'count' column to the table :-)

Community
  • 1
  • 1
Alex
  • 16,739
  • 1
  • 28
  • 51
  • Am I wrong? I am pretty sure the problem is there - Model attributes declaration... :-) – Alex Jan 09 '15 at 16:13