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
6
  • 1
    $count = 0;, $count = $count + 1;, then you try to use $count->toArray()? You're treating an integer like an object. Commented Jan 9, 2015 at 15:17
  • @sjagr : what do you suggest in order to fix this ? can you help me please Commented Jan 9, 2015 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. Commented Jan 9, 2015 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. Commented Jan 9, 2015 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 Commented Jan 9, 2015 at 15:33

3 Answers 3

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;
});
Sign up to request clarification or add additional context in comments.

2 Comments

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. :)
What do you mean? The .length of php is count(). Or maybe I don't understand your question correctly...
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);

Comments

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 :-)

1 Comment

Am I wrong? I am pretty sure the problem is there - Model attributes declaration... :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.