0

I have this code where I want to select certain values from the table. Counter is my Model.

$today = '2022-03-16';
$tanggal = Counter::select('tanggal')->where('api', 'Agenda')->where('tanggal', $today)->get();

But if i dd($tanggal->tanggal), it returns with an error Property [tanggal] does not exist on this collection instance.

How to get a value from 'tanggal' attribute?

1
  • 5
    get() returns a collection. A collection is an array of objects. So you need to loop through that array to access individual instances. I suppose what you should be using here is first() instead of get() but that is if you are expecting only one record. Otherwise, yeah. loop. Commented Mar 15, 2022 at 12:08

3 Answers 3

1

You are using get() method. it will return collection. You can not access any field directly from collection. You have to need use freach loop to access single property.

$today = '2022-03-16';
$tanggals = Counter::select('tanggal')
    ->where('api', 'Agenda')->where('tanggal', $today)->get();
forech( $tanggals as  $tanggal)
{
    dump($tanggal->tanggal);
}
Sign up to request clarification or add additional context in comments.

Comments

0

You are trying to access a model property from a Collection, this can be fixed like so:

$tanggal = Counter::where(['api' => 'Agenda', 'tanggal' => $today])->first(['tanggal']);

get() returns a Collection, first() returns a Model.

Comments

0

You can use the collection but then use its .each() method and give it a lambda instead to process each value.

$collection = Counter::select('tanggal')->where('api', 'Agenda')->where('tanggal', $today)->get();
$collection->each(function ($item, $key) { 
    //write now your code here  can do $item->tanggal

});

Comments

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.