php - Laravel - A model is not passed to first() method's closure

758

I have a{-code-1} and I am callingfirst() method on it with a closure expecting a parameter say$model.

Upon execution, if I try to access a property of$model; it says:

Accessing property of non-object

I tried dumping$model and found that it has a integer1 instead ofObject.

$Collection->first( function($model) {
    if(!$model) return false;
    return $model->type == 'Test';
});
717

Answer

Solution:

I just got it working. Thefirst() method's argument closure is provided with 2 variables. First one is the key and second one is the model. So, you will callfirst() method like below and if it satisfies the criteria you defined, just returntrue.

$result = $collection->first( function($i, $model) {
    // define criteria and return true if it satisfies. The model will now be returned in resulting Collection.
});

People are also looking for solutions to the problem: php - Group rows by column value and within groups create new sum column and count column

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.