How to get a value from database on Laravel Controller? - laravel

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?

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);
}

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.

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
});

Related

How to compare two objects and get different columns in Laravel

I have two objects of the same record which I am getting from the database. One is before the update, and the other is after the update. I want to know the column values which are changed during this update query.
$before_update = DeliveryRun::find($id);
$before_update->name = $request->input('name');
$before_update->save();
$after_update = DeliveryRun::find($id);
compare($before_update, $after_update)
I would define a method on your DeliveryRun model which can be used to compare objects of the same type.
Lets say we want to be able to do something like $deliveryRun->compareTo($otherDeliveryRun). That seems like a nice fluid syntax and reads well in my opinion.
What we want to do is get the attributes and their values for the DeliveryRun we're calling compareTo on and then compare them against the attributes and values for the DeliveryRun we provide as an arguement to the compareTo method.
class DeliveryRun extends Model
{
public function compareTo(DeliveryRun $other)
{
$attributes = collect($this->getAttributes())
->map(function ($attribute, $key) use ($other) {
if ($attribute != $other->$key) {
return $key = $attribute;
}
})->reject(function ($attribute, $key) {
return !$attribute || in_array($key, ['id', 'created_at', 'updated_at']);
});
return $attributes;
}
}
The above gets the attributes for the current ($this) DeliveryRun, converts the array returned from getAttributes() to a collection so we can use the map() function and then loops over each attribute on the DeliveryRun model comparing the key and value of each against the $other DeliveryRun model provided.
The reject() call is used to remove attributes which are the same and some attribute keys which you might not be interested in leaving you just the attributes that have changed.
Update
I am saving object in other variable before update $before_update = $delivery_run; but after update $before_update variable I also gets updated
If I am understanding you correctly, you're still comparing the same object to itself. Try something like the following.
$before = clone $delivery_run; // use clone to force a copy
$delivery_run->name = 'something';
$delivery_run->save();
$difference = $before->compareTo($delivery_run);
I would consider using getChanges() as suggested by #Clément Baconnier if all you're doing is looking to get the changes of an object straight after the object has been saved/updated.

How to get item from laravel eloquent collection by conditions?

I use laravel eloquent to get files of post that give me a collection
but I want an item from that collection by condition.
For example from that collection I want an item that type = 'product'.
I am using foreach and check every item that have my condition and return it, but isn't any better way?
I tested collection method like contain but it return null.
Files item have type filed that value is 'product' or 'blog'.
My code:
$post= Post::where('slug' , $slug)->first();
$cover = $post->files->contains(['type' , '=' , 'product']);
Use the collection filter method.
$cover = $post->files->filter(function($file) {
// show only the items that match this condition
return collect(['product', 'blog'])->contains($file->type);
});
The filter method filters the collection using the given callback, keeping only those items that pass a given truth test:
$filtered = $post->files->filter(function ($value, $key) {
return $value->type == 'product';
});
$filtered->all();
Collections - filter()

how to display name from database in laravel

i want to display data from my database
controller
public function generatePDF(Request $request)
{
$id = Auth::user()->id;
$name = User::select("NAME")->where("id", $id)->get();
$pdf = PDF::loadView('generatePDF', ['name'=>$name]);
return $pdf->stream('generatePDF.pdf');
}
blade
<h2>{{name}}</h2>
result
[{"NAME":"name_from_database"}]
can i display without [{"name":}], so just the value of data (name_from_database) ?
Simple use find like this
$name = User::find($id)->name;
Or direct from auth
$name = \Auth::user()->name;
To get logged in user id you can use \Auth::id()
you can use:
$user_id = User::findOrFail($id)->first();
$name=$user_id->name;
test the laravel log file:
\Log::info($name);
Use first() instead of get(), because get() will return an array and first() will return the object.
DRY Code line no.1 and no.2. simple use:
$name = auth()->user()->name;
to get the name of the currently authenticated user.
Send $name to you view is fine
$pdf = PDF::loadView('generatePDF', ['name' => $name]);
Correct your code in blade file
{{ name }} -> {{ $name }}
I hope this might help you. :)
Hello Aldi Rostiawan,
$nameGet = User::select("NAME")->where("id", $id)->get();
$nameFirst = User::select("NAME")->where("id", $id)->first();
Here in both line of code the difference is only Get and First.
Get method returns an Array of objects. So for example if the query apply on many records then the code will give you many objects in an array. Or if query will be true for only one record then also it will return an array with one object.
If you know that id is primary key of he table then only one record will be fetched then you can use First function instead if Get method.
First function always return an Object. In case if query apply on many records then also first method will return you only first record as an Object.
And it seems that you have required an Object only.
You should try this:
Controller
public function generatePDF(Request $request)
{
$id = Auth::user()->id;
$rsltUser = User::where("id", $id)->first();
$pdf = PDF::loadView('generatePDF', ['rsltUser'=>$rsltUser]);
return $pdf->stream('generatePDF.pdf');
}
blade
<h2>{{$rsltUser->name}}</h2>
use VALUE() to display name only.
in your case:
<h2>{{$rsltUser->value('name')}}</h2>
your name variable is an array containing a single object with a NAME attribute .. so to diplay that value, you should change your script to
<h2>{{name[0]['NAME']}}</h2>

Eloquent Return Non Associative Array?

I am trying to get an array list of IDs to pass onto another model query.
$companies = $user->companies->pluck('id');
But it keeps returning an associative array as such:
[ 0 => 2, 1 => 9]
So when I pass it to the find method on my Company model, like this
$company = Company::find($companies);
I get the following error:
Trying to get property of non-object
I need to be able to pass a non-associative array to the call like such:
Company::find([2,9]);
Try that:
$companies = $user->companies->pluck('id')->toArray();
Just did a test in tinker and the result is a flat array, the "find" will work for sure!
As you can see in Laravels source code
src/Illuminate/Database/Eloquent/Builder.php
public function find($id, $columns = ['*'])
{
if (is_array($id)) {
return $this->findMany($id, $columns);
}
$this->query->where($this->model->getQualifiedKeyName(), '=', $id);
return $this->first($columns);
}
find() will internally call findMany() if the first parameter is an array. But $user->companies->pluck('id') returns a Collection and the Builder creates a wrong query. So your options are:
Use findMany():
$company = Company::findMany($companies);
Convert the Collection to an array:
$company = Company::find($companies->toArray());
Use whereIn():
$company = Company::whereIn('id', $companies)->get();
But actually that all doesn't seem to make any sense, because $user->companies probably already contains the collection you want to fetch from DB. So you could also write:
$company = $user->companies;
However - the fact that you are using singular naming (company) for a set of companies, let me think that you are trying to achieve something completely different.
You can try with the whereIn method
Company::whereIn('id', $companies)->get();

how to put and retrieve laravel collection object on Session

I know that we can insert array in Session as Session::push('person.name','torres') but how to keep laravel collection object such as $product = Product::all();,as like Session::put('product',$product);.Ho wto achieve this?
You can put any data inside the session, including objects. Seeing as a Collection is just an object, you can do the same.
For example:
$products = Product::all();
Session::put('products', $products);
dd(Session::get('products'));
Should echo out the collection.
You should convert it to a plain array, then convert them back to models:
Storing in the session
$products = Product::all()->map(function ($product) {
return $product->getAttributes();
})->all();
Session::put('products', $products);
Retrieving from the session
$products = Product::hydrate(Session::get('products'));
You can see an example of this method here.

Resources