'How to get a value from database on Laravel Controller?

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?



Solution 1:[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);
}

Solution 2:[2]

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.

Solution 3:[3]

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

});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dilshad
Solution 2 xandrw
Solution 3 whizboy