I am using Doctrine 1.2 with Zend Framework. When I fetch a result set as a Doctrine collection, the collection object contains an empty model object of a given type if the returned result-set returned from the DB is empty.
This is quite confusing as we are relying on the count method of Doctrine_Collection to show either a listing of the returned results or an appropriate message when the query returns an empty collection.
Any help will be highly appreciated.
I also thought this was annoying. You want to test for actual results by calling Doctrine_Collection::count(), such as this scenario that we had:
if ( $collection->count() ) {
// display some widget of the members of Doctrine_Collection
}
The method suggested by yitznewton works for me.
Alternatively, you can test a known field for the first element (0) in the collection.
if ($collection[0]->id) {}
Related
I'm trying to get the data without using eager loading in a Eloquent Model but I needed to cast it into Array to use in some part of the code.
In order words, I wanna just get the data like this example:
$invoice->invoice_type_id->name;
Since it's an array what I'm writing is: nfe['invoice_type_id']['name']
But I'm getting this error (because it's an array):
Trying to get property of non object
So, my query is:
Invoice::query()->where('order_id', $order_id)->get()->toArray();
And my model I already have the relationship declared:
public function invoiceType()
{
return $this->belongsTo(InvoiceType::class);
}
Generally speaking, I am trying to remove an object from a laravel collection of objects. I do not wish to convert the collection to an array to do this task, as this invalidates any real reason to use collections in the first place. Nor do I wish to delete the underlying model from the database - I just wish to remove the record from the collection.
Looking at the docs for available methods I don't see a simple way to complete this task.
Laravel Collections have a variety of methods. The search method looks very promising,
The search method searches the collection for the given value and returns its key if found.
I was planning to use the returned key with the forget method to dispose of the unwanted object.
The forget method removes an item from the collection by its key
However, every example I can find for the "search" method uses only a simple collection of integers or strings to show functionality. I am looking to search within the objects included in the collection.
We have the following variables:
$coll // a collection of objects taken from a database.
// Each object contains a field called "invoice_number" that I am trying to match.
$invoice_number // the invoice number associated with the object
// I wish to remove from $coll
$tmp_object = $coll->firstWhere('invoice_number', $invoice_number); // the needle for the haystack
Any assistance in finding a solution to the problem using collections is appreciated, especially using the "search" method.
Thank you.
you can use the "filter" method :
$coll = $coll->filter(function($invoice) use ($invoice_number){
return $invoice->invoice_number != $invoice_number;
});
if your invoice_number is unique, you can do this :
$coll = $coll->keyBy('invoice_number');
$coll[$invoice_number];
to retrieve it and
$coll->forget($invoice_number);
to only remove it from your collection
you can use filter:
$res = $coll->filter(function($el) use($invoice_number){
return $el->invoice_number != $invoice_number;
});
I have a pages controller.I wanna get some information stored in my db when /myshopping requested.
This is my controller code :
public function myshopping()
{
$Buylist=DB::table('orders')->where('id','=',Auth::user()->id)->orderBy('oId','desc')->get();
$Bookinfo=DB::table('books')->where('bId','=',$Buylist->bId)->first();
return view('shop.myshopping',compact('Buylist','Bookinfo'));
}
Thank you very much.
Using->get() on a QueryBuilder returns a Collection (fancy wrapper for PHP arrays), so $Buylist is a group of records from your orders table, as opposed to a single record.
If you change your logic to use ->first():
$Buylist=DB::table('orders')->where('id','=',Auth::user()->id)->orderBy('oId','desc')->first();
Then you can access $BuyList->bId without issue (unless $BuyList returns null, but that's a different issue).
I need to understand when/not to use get(); in Laravel 5.
PHP warning: Missing argument 1 for Illuminate\Support\Collection::get()
Google shows me answers to their issue but no one really explains when you should/not use it.
Example:
App\User::first()->timesheets->where('is_completed', true)->get(); // error
App\Timesheet::where('is_completed', true)->get(); // no error
Fix:
App\User::first()->timesheets()->where('is_completed', true)->get(); // no error
Noticed the timesheets() and not timesheets? Could I have a detail explanation for what is going on, please?
I'm coming from a Ruby background and my code is failing as I do not know when to use () or not.
I'll try to describe this as best I can, this () notation after a property returns an instance of a builder, let's take an example on relationships,
Say you have a User model that has a one-to-many relationship with Posts,
If you did it like this:
$user = App\User::first();
$user->posts();
This here will return a relationship instance because you appended the (), now when should you append the ()? you should do it whenever you want to chain other methods on it, for example:
$user->posts()->where('some query here')->first();
Now I will have a the one item I wanted.
And if I needed say all posts I can do this:
$user->posts;
or this
$user->posts()->latest()->get();
$user->posts()->all()->get();
So the key thing here is, whenever you want to chain methods onto an eloquent query use the (), if you just want to retrieve records or access properties directly on those records then do it like this:
$user->posts->title;
Well, ->timesheet returns a collection, where ->timesheet() returns a builder.
On a Collection you can use ->where(), and ->get('fieldname'), but no ->get().
The ->get() method can be used on a builder though, but this will return a collection based on the builder.
Hope this helps.
The 'problem' you are facing is due to the feature of being able to query relations
When accessing a relation like a property, ->timesheets, the query defined in the relationship is executed and the result (in the form of a Collection) is returned to you.
When accessing it like a method, ->timesheets(), the query builder is returned instead of the resulting collection, allowing you to modify the query if you desire. Since it is then a Builder object, you need to call get() to get the actual result, which is not needed in the first case.
When you use ->timesheets you are accessing a variable, which returns the value of it (in this case an instance of Collection).
When you use ->timesheets() you are invoking whatever is assigned to the variable, which in this case returns an instance of Builder.
whilst pascalvgemert's answer does answer your problem regarding Laravel, it does not explain the difference between accessing or invoking a variable.
In simple term
$user = App\User::get();
is used to fetch multiple data from database
rather
$user = App\User::first();
is used to fetch single record from database
I am using laravel-permission for managing roles and displaying content. Per the docs you can retrieve a users roles by using $roles = $user->roles()->pluck('name'). My problem is that the data returned is ["admin"] rather than just admin. I was reviewing the collections methods and it looked like get('name') would return what I was looking for. When I try to use the following command Auth::user()->roles()->get('name') I get
1/1
ErrorException in BelongsToMany.php line 360:
Argument 1 passed to Illuminate\Database\Eloquent\Relations\BelongsToMany::getSelectColumns() must be of the type array, string given
It seems to me like the get() method is expecting an array however, I'm trying to reference an item in the array. The raw output of Auth::user()->roles()->get() is [{"id":1,"name":"admin","created_at":"2016-03-10 06:24:47","updated_at":"2016-03-10 06:24:47","pivot":{"user_id":1,"role_id":1}}]
I have found a workaround for pulling the correct content, but it is using regex for removing the unwanted characters that are included in the pluck() method.
preg_replace('/\W/i','', Auth::user()->roles()->pluck('name'))
It seems like I'm missing something or approaching using the get() method incorrectly. Any advice is appreciated.
I think pluck() will return the value of the given column for each model in the collection, which would explain the array. In your case it looks like the user has only one role, so you get an array with only one item. If the user had multiple roles, you would likely get an array with multiple items in it.
On the other hand, the get() method is used to execute a query against the database after a query is built. The results of the query are what is returned. To return a collection of models with only a single value you will need to pass an array with just the one column you want, but that will just select models, which does not appear to be what you ultimately need.
You can try this instead: $roles = $user->roles()->first()->name
The call to first() will grab the first model in the collection returned by roles(), and then you can grab the name of the role from that model.
I typically throw some error checking around this:
$role = $user->roles()->first();
if (is_null($role)) {
//Handle what happens if no role comes back
}
$role_name = $role->name;
That's because an user can have many roles, so roles is a collection.
If you are 100% sure that a user will have only one role, you can easily do
Auth::user()->roles()->first()->name
That will get the first item of that collection (the role) and then its name.