Simplifying the output of a Laravel model query - php

Suppose I run the following and need to know the results in an easy to examine format:
$orders = Order::where('status', $value);
How would I show something that doesn't display the entire model object, only the records retrieved, when I do dd($orders)?

You may try this:
$orders = Order::where('status', $value)->get();
dd($orders->toArray()); // Outputs only an array of records retrieved from db
There is also toJson() to convert into json string but it's possible to get json representation of the data by returning it from the controller/function, for example:
return Order::where('status', $value)->get(); // Output will be in json format

Instead of dding, just return the model directly from your route/controller:
return Order::where('status', $value)->get();
This will automatically convert it to JSON.
For even better inspection, install the JSON View Chrome extension; it'll format your JSON nicely, and allow you to inspect it beautifully.

Related

Howv to assign multiple result of query laravel php

New to Laravel php and trying to find out solution of this,
$periods = Period::where('timetable_id', $id);
echo $periods;
giving this error
Object of class Illuminate\Database\Eloquent\Builder could not be converted to string
i know why its giving this error but can not think of an alternate.
You'd need to ->get() your results first. Also, since you'll get a Collection returned you'd need to use dd() (or print_r/var_dump) to output the results:
$periods = Period::where('timetable_id', $id)->get();
dd($periods);
More on Building Queries

Laravel Eloquent query JSON column with Where In?

I am having trouble querying a json column.
Previously my code was
$query->whereIn('user', $users);
Now i have changed the db type to JSON column and am trying to modify the code for the new version.
In RAW MYSQL this works
JSON_CONTAINS(user, '"tom","Bill"')
But when i put it in eloquent / php it keeps failing or returning noting. Here i am passing in an array of Users, previous using an WhereIn which works in raw SQL
$leads->whereRaw("JSON_CONTAINS(user, '"$users"')")
Any idea how to make it work in Laravel so i can pass in an array of strings, query them against the json column which contains an array of strings too.
My Json colum has data like so
["Paul", "Tom", "Bob"]
MySQL expects a JSON string:
$leads->whereRaw('JSON_CONTAINS(user, ?)', [json_encode($users)])
In Laravel 5.6.24 you can use whereJsonContains():
$leads->whereJsonContains('user', $users)
If $users is array of names then you should iterate over it and add orWhereRaw condition, note that orWhereRaw can accept an array of parameter:
$users = ["Tom", "Bob"];
foreach( $users as $user) {
$leads->orWhereRaw("JSON_CONTAINS(user, ?)", [$user]);
}
$leads = $leads->get();

Laravel get single column result as string

Hello I would like to know is it possible to get column value as string. Instead of array in array:
Current query: Number::limit('1000')->get(['number'])->toArray()
The result at the moment is this:
Preferable result:
Before your toArray() call, add pluck('number'):
$result = Number::limit('1000')->get(['number'])->pluck('number')->toArray();
That's it! This will pluck just the number attributes from your result collection, and give you a single-level array.
The reason this works, is because you are getting a Collection back from get():
All multi-result sets returned by Eloquent are an instance of the Illuminate\Database\Eloquent\Collection object, including results retrieved via the get method or accessed via a relationship.
And the pluck method:
https://laravel.com/docs/5.1/collections#method-pluck
Update
Another, even more succinct method provided by #wunch in the comments:
$result = Number::limit('1000')->lists('number')->toArray();

Retrieve a json field from mysql field with PDO

I have a database where I store some data, and one field is a json string.
I insert an json in this field:
$stmt->bindParam(":settings", json_encode($widget->settings));
Then when I try to retrieve the record I get my row with the settings column as string. I need my data to be json, so I should decode this field before output my records. If i go with:
$app->response->setBody(json_encode($data, JSON_NUMERIC_CHECK));
I get something like:
"name":"My Name","label":null,"row":null,"settings":"{\"site\":\"dfsdf\",\"action\":\"UrlInfo\"}"
with settings escaped. I should first decode settings and then encode again to output my results. How can I do to solve this?
UPDATE:
I retrieve my data using PDO, so I get an array:
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
Before I save this I have:
"settings":{"site":"fff","action":"UrlInfo"}}
When you retrieve the data, you should use json_decode to reverse the encoding that you did when you inserted it.
foreach ($data as &$row) { // Use reference so we can modify in place
$row['settings'] = json_decode($row['settings']);
}
$app->response->setBody(json_encode($data, JSON_NUMERIC_CHECK));

Need a INT from Eloquent. Getting JSON string

I have this query:
static function findIdOnName($pageName){
return Fanpages::select('id')
->where('url', '=', $pageName)
->get();
}
Response: (when done print_r)
[{"id":17}]
I just want the INT (in this case 17) I searched the interwebs for it, but I can't find anthing about it. Randomly tried adding ->toString() etc to the query, but so far, no good.
Your code returns a Collection with a single Model (or multiple models if there are more matching the where clause), while the method you need is pluck:
return Fanpages::where('url', '=', $pageName)->pluck('id');
// returns INT 17
as it returns value for column id of the first row matching WHERE clause.
If you do not return a view with data, then Laravel will automatically convert your data into json. In order to accomplish what you want you can simply do something like
$data = Fanpages::select('id')->where('url', '=', $pageName)->get();
die($data->id);
However, exiting the application like this isn't recommended. You should either keep the json response and work with that, or send the data to a basic blade template.

Categories