This is my object
{
"id":1,
"name":"abc",
"tech":"PHP"
}
now i want to get value of tech using User eloquent model using laravel collection method first
this is my eloquent model query
$tech = User::select('tech')->first();
but it return data is form of object like this
{"tech":"PHP"}
i want only value in string formate not in object like it should return "PHP".
can any one help?
You can use the pluck function for this.
$tech = User::pluck('tech')->first();
This will return:
"php"
Your code
$tech = User::select('tech')->first();
as you said
Actually it will returns the object
{"tech":"PHP"}
try this to get the result the
$tech = User::select('tech')->first()->tech;
not as
$tech = User::select('tech')->first();
Related
$product=ProductCatalog::where(['campaign_id' => $campaign_id])->get();
print($product);
OUTPUT:
[{"id":7,"campaign_id":64,"product_id":26,"created_at":"2018-03-20 10:29:51","updated_at":"2018-03-20 10:29:51"},{"id":8,"campaign_id":64,"product_id":27,"created_at":"2018-03-20 10:30:26","updated_at":"2018-03-20 10:30:26"}]
From $product i want to fetch value of product_id
How to fetch value from $product?
please help me with this problem...
You can use toArray() of eloquent as below.
The toArray method converts the collection into a plain PHP array. If the collection's values are Eloquent models, the models will also be converted to arrays.
$product = ProductCatalog::where(['campaign_id' => $campaign_id])->get()->toArray();
And then you can access the array properties as per your need. See sample below.
foreach($product as $productValue) {
print_r($productValue['product_id']);
}
$productCatalogs = ProductCatalog::with('product')->where(['campaign_id' => $campaign_id])->get();
foreach($productCatalogs as $productCatalog){
print_r($productCatalog->product);
}
This should work if you have defined relationship in ProductCatalog Model (ProductCatalog.php).
I've a very big doubt about how works laravel for a very simple thing:
If I call:
$companies=User::All();
Then I can use statement like this in a forach:
foreach($companies as $company)
$company['new_field']= 'something';
If i'm limiting the output of the query like:
$companies = DB::table('companies')
->select('id','name','email','business_name',...)->get();
The things doesnt work as before,
I try with or without the ->get()
I try to convert with ->toArray() (errors rised)
I try with put() and push() for collections method and agains errors...
How can I add a field in every item of the collection just to pass it to a view?
Try like this, hope it works for you:
$users=User::select('id','name','email','business_name',...)->get()->toArray();
and then use foreach loop like this:
foreach($users as $key => $value ){
$users[$key]['newField'] = "Demo";
}
If you are using Laravel and model in it so there is a better way to add custom attribute or field here is what i do for custom field
For Example :
There is a Model Name User
so in User Model
add a property name appends like :
class User extends Model
{
protected $appends = ['new_field'];
public function getNewFieldAttribute() // defining field logic here
{
return // your code
}
So you no need to use foreach and looping and adding new field
for more have a look on laravel doc : https://laravel.com/docs/5.5/eloquent-mutators#accessors-and-mutators
Suggestion
you can limit your output with Model too.
User::select('id','name','email','business_name',...)->get();
if you are making an array like
User::select('id','name','email','business_name',...)->get()->toArray();
so this will also give you your custom field
I try like this
Data type of votes_detail in database is json
My model like this :
<?php
class Store extends Model{
protected $fillable = [ ...,'votes_detail',...];
protected $casts = [
'votes_detail' => 'array',
];
}
My controller like this :
$store = Store::find($id)
$votes_detail = $store->votes_detail;
dd($votes_detail);
The result of dd($votes_detail) is :
{"1": "1", "5": "2"}
Why the result is still json?
The result should be an array
Whereas I've set the array in cast model
How can I solve this problem?
You could use Laravel accessors. In you model define a method called exactly getVotesDetailAttribute($details):
public function getVotesDetailAttribute($details)
{
return json_decode($details, true);
}
then when you will call $store->votes_detail you will get the expected result.
After that you can use mutators to convert an array back to JSON when it is saved back in the DB. Define the method setVotesDetailAttribute($value) as follows:
public function setVotesDetailsAttribute($value)
{
$this->attributes['votes_detail'] = json_encode($value);
}
You can easily do it by converting your data to the array by using toArray() function. So it should be like
$store = Store::find($id)->toArray();
//$store contain a array.
$votes_detail = $store['votes_detail'];
make it dd($votes_detail) and get your desire result.
I think you are storing array data after json_encode() to a column which is not defined as json() in the migration like:
$table->text('votes_detail');
or
$table->integer('votes_detail');
And seems you have defined votes_detail as string, number or something else.
This is the reason behind your problem. So, define column type as json in migration like:
$table->json('votes_detail');
And then refresh your migration, your casting in the model will work and you will get your desired array.
I have problem with Doctrine query in my Symfony2 project.
That my code:
public function getLender($lender) {
$lender = str_replace("_", " ", $lender);
$this->qb->select('ld, ld.entry, ll.name, ll.logo')
->from('PageMainBundle:LoanDescription', 'ld')
->leftJoin(
'PageMainBundle:loanLender',
'll',
\Doctrine\ORM\Query\Expr\Join::WITH,
'ld.lender = ll.lenderId'
)
->where('ll.name=?1')
->setParameter(1, $lender);
return $this->qb->getQuery()->getResult();
}
When in select section i choose columns it works very well - returns values of columns. unforunelly when I try something like that:
$this->qb->select('ld')
I don't get pure values but sometkhing strange.
How can I get values of all db columns?
This "strange" thing is most probably an LoanDescription collection of object (entity) instances. So to get value of entry field you need to call $entity->getEntry() on this entity object (assuming that you have such method defined in your entity)
OR
You can use getArrayResult instead of getResult and you should get array with valies
I'm currently trying to create my settings page by creating a table settings with company_name column. My idea is to fetch the single value company_name and print it in the title of the pages and where the name is going to be appearing. I just am not sure how to convert the array return from the DB::select to be able to print it correctly.
The code:
public function __construct()
{
$company_name = DB::table('settings')->select('company_name')->get();
return View::share('company_name', $company_name);
}
And print it in the blade system as {{ $company_name }}, although it can't convert an array to string.
Either use eloquent (that I would recommend) which would be like this :
$company_name = Setting::first()->company_name;
or using fluent :
$company_name = DB::table('settings')->company_name;
Could you use ->first() to select the first value from the returned set?
I think you should re-think your DB schema.
But if you want an answer to keep working with you current schema:
DB::table('settings')->select('company_name')->first();
This can throw an Eloquent ModelNotFound exception.
EDIT
public function __construct()
{
$result = DB::table('settings')->select('company_name')->first()->toArray();
return View::share($result);
}