Access a protected field from queried Eloquent object - php

I query an entity:
$trip_redirect_id = Trip::whereUniqueToken($unique_token)->select('id')->get();
and try to get the id value with $trip_redirect_id->id or $trip_redirect_id['id'] but I get exception that the field is not present.
When I dump the $trip_redirect_id object, I can see the id and it's value and they are correct (I checked with the database). But how can I access the value inside php?

You are using get() which is going to be returning a Collection of objects so you won't be able to get the attributes of the models unless you iterate through the collection, even if it's just one item in the collection, or just grab the first record. Use this instead:
Trip::whereUniqueToken($unique_token)->select('id')->first();

Turns out, if I use auto-incrementing IDs, I can access the id attribute of the newly created model, right after it has been created in the DB.
So, this is the whole fix:
$trip->save();
$trip_redirect_id = $trip->id;

Related

Check if the user is attached or not yet

I'm working with Laravel on little project, i have a pivot table and I would like to attach new users, but I must check if the user is not already attached. how can I do ?
$user = User::findOrFail(2);
$user->liked()->attach(6);
dd($user);
How can I check if the user number 6 is already attached or not, so i can add the new record.
You may also use the sync method to construct many-to-many associations. The sync method accepts an array of IDs to place on the intermediate table. Any IDs that are not in the given array will be removed from the intermediate table. So, after this operation is complete, only the IDs in the given array will exist in the intermediate table:
$user = User::findOrFail(2);
$user->liked()->sync([6,//ids you want attach]);
dd($user);
If you do not want to detach existing IDs that are missing from the given array, you may use the syncWithoutDetaching method:
$user->liked()->syncWithoutDetaching([1, 2, 3]);
Also Refer This

id attribute in eloquent collection changes when converting to an array

I have a database with uuid's as the id column. I do a query using eloquent and it returns the correct information. I have attached an image below because its a big object to write.
So theres 2 items in this collection, they follow the same format but as you can see the first item has the id field which is the correct uuid.
To print this i am doing
$offers = Offer::list($display, false);
dd($offers);
So offers is the collection.
If i do...
$offers = Offer::list($display, false);
dd($offers->toArray());
I get the following...
The id has magically changed into single integers instead of the uuid string I had before.
Does anyone know why it would be doing this? thanks
Set the $incrementing property on your model to false, it is documented here on the primary keys section. By default Laravel assumes that the id field on your model is an incrementing integer, that is why models automatically cast id fields to integers.

Laravel model object retrieving relation model with where condition without "get" method

I'm working on octoberCMS(laravel framework), I have a doubt on retrieving relation model on where clause.
I have fetched a clothing_type record from "clothing type" model based on its primary key "id".
$clothing_type = ClothingType::where('id',post('clothingtype_id'))->where('status','Active')->first();
This "clothing type" model is related with "products" model, the relation is => each clothing type hasMany products.
Every thing works fine; Now my business logic has two cases, one is to get all the products of the clothing type and another is to get the first product of the clothing type. So I have used the $clothing_type->products to get all the products and $clothing_type->products->first() to get the first product.
Now I have to apply a condition for both the cases. The condition is that only the product whose status is "Active" should be fetched, hence
$products = $clothing_type->products->where('status','Active'); and$first_product_detail = $products->first();.
Every thing works as expected but how come the products are fetched without "get()" method. $clothing_type->products->where('status','Active')->get(); Since I'm new to relation I want to know how this works or is this a bad way to get records or improper assumption. But every thing works good.
$clothing_type = ClothingType::where('id',post('clothingtype_id'))->where('status','Active')->first();
if(count($clothing_type->products))
{
$products = $clothing_type->products->where('status','Active');
$first_product_detail = $products->first();
}
You are doing it the correct way. When you access the relationship as an attribute Eloquent automatically retrieves the records.
However, if you access the relationship as a method, you get the query itself, to which you can add your filters:
if(count($clothing_type->products))
{
$products = $clothing_type->products()->where('status','Active')->get();
$first_product_detail = $products->first();
}
This would solve your problems
(documentation is over here (see the first item))
Edit: Also note that the first method is not a method of Eloquent, but from Collection, which is pretty powerful!
Edit2:
I misread the part of your question where you want to know HOW this is possible. Both Eloquent and Collections have a where method. I assume you understand the working of the Eloquent one, but the one from Collection is pretty much the same (see documentation on the Collection where here)
I prefer the Eloquent one myself, because that limits the amount of records that is retrieved from the database. But if you need all the products (even the inactive ones) later on in your code, just use the Collection method to filter the active ones out
There is nothing to be afraid of...
first() and where()
are functions of both Illuminate\Database\Query\Builder as well as Illuminate\Support\Collection and all first does is limit the records to take 1 and then give you the first record. When you use Builder a query is made to get 1 record and 1 you use it on a collection, all records are first get() and then the first of those records is returned.
Here,
When you do,
$clothing_type->products, Laravel gives you a collection of products...
So...
$products is an object of Illuminate\Support\Collection
and
$products->first() calls for the first() function in that class.
Documentation on where and first methods of a collection...

Make every function in a PHP class refer to the same database row

Looking to make a class that will be for 'customers'. The purpose of this class is to pass in some details, and then either add a user or update an existing one.
After this, I might also want to do to more things with this 'customer'.
Im new to classes so need to know how to always refer to the same row no matter what i'm doing with the current initiated class.
Basic use:
$customer = new Customer($customer_details);
When creating a new instance of this class, I want it to straight away add / update a row.
However, as well as this later on I might want to update a specific field:
$customer->setValue('firstname','Craig');
But I dont want to have to do another lookup to get the row ID etc in this fucntion. I want $customer to always reference the user given the $customer_info.
Assuming you want setValue() to update the database, I would advise creating a field in your Customer class that contains the identifier for the row in the database.
/**
* Database identifier.
*
* #var string/int
*/
private $id;
Have your constructor set the value of the identifier on object creation using $this->id = $id. Then your setValue() call can use that identifier to update the information in the database.
EDIT
If you are creating a new Customer instead of updating an existing one (passing new data to the constructor) the database controller that you are using should have a means to get the ID of the new row (given it is an auto-incremented value). Otherwise the ID is something that you are generating, in which case you could just set the field value in the class.
I think you're referring to the Active Record Pattern. You can find many implementations in PHP, such as Propel.

Laravel Query - pulling value from array

this has been driving me nuts...
I'm in my view I'm calling
Auth::user()->userlists
which brings me back an array of values like
{"id":"1","user_id":"1","name":"list1".....}
all I want to do is bring back the names I've tried all these;
Auth::user()->userlists->name
Auth::user()->userlists()->name
Auth::user()->userlists->name->get()
Auth::user()->userlists.name
But I always get an error such as "Undefined property"
How do I return this single property, it's in my array for all the items but I'm clearly just getting the syntax incorrect...?
The reason i'm trying to do this is that I need the values placed in a drop down box, it's finding the correct rows in the table but displaying all the data instead of just the name
Form::select('userlist_id', Auth::user()->userlists);
Many thanks.
You say a User has many Userlist models, so it's a collection not single model, thus you could work with it in a loop, BUT there is better way:
$lists = Auth::user()->userlists()->lists('name','id');
// To make it available in all the views, place this for example in a controller:
View::share('userlists', $lists);
This will fetch id and name for the related models collection and return it as an array, so it's just the one you will use in a Form builder:
Form::select('userlist_id', $lists)

Categories