I'm trying to get a list of categories and return them as JSON for an AJAX call, but Laravel is including column names too, which I don't need.
$categories = Category::where('parent', '=', '0')->select('name')->get();
return response()->json($categories);
This way I get
[{"column_name", "value"}]
And I want
{"value1", "value2"}
Thanks!
Try this: $arr = json_decode($categories, true). Then deal with the array output it gives.
You simply use eloquent's lists method
$categories = Category::where('parent', '=', '0')->select('name')->lists('name');
return response()->json($categories);
Use array_values function to get the values array.
And {"value1", "value2"}the format is invalid of Json . Valid format ["value1","value2"] . If use { } means to Object ,but object must have key=>value.
$categories = Category::where('parent', '=', '0')->select('name')->get();
return response()->json(array_values($categories));
Related
I have a database column called support_tags. This is a jsonb column containing a simple array that looks like:
[
"caring",
"budgets",
"careers_employment",
"addictions"
]
I am attempting to query this column using the following:
$services = \App\Models\Service::where("status", "accepted")->whereRaw("JSON_CONTAINS(support_tags, '" . json_encode($categories) . "')")->get();
This doesn't retrieve the results I am hoping for/expecting. If I send the following array:
[
"caring",
"smoking"
]
The results I get back are services that contain all array elements. I need this to work more like a whereIn, in that not all array values need to be present in the database column, but one or more. If anyone knows of a way to do this I'd be very grateful. Thanks.
you can use these eloquent methods: ->whereJsonContains() and ->orWhereJsonContains()
your query will be like this:
$services = \App\Models\Service::where("status", "accepted")
->where(function($query) {
$query->whereJsonContains('support_tags', 'smoking')
->orWhereJsonContains('support_tags', 'caring');
});
Just before I accept the other answer to this question, I thought it may be useful to share my implementation of this which is based on the accepted answer This does the trick:
$categories = request()->infoAdviceCategories;
$services = [];
if (count($categories)) {
$services = \App\Models\Service::where("status", "accepted")->whereJsonContains("support_tags", $categories[0]);
foreach ($categories as $category) {
if ($category !== $categories[0]) {
$services->orWhereJsonContains("support_tags", $category);
}
}
$services = $services->get();
}
return $services;
I am trying to loop through an array of ids to get data from another table, I mean I want to get latest queues of every schedule id we are looping in it.
So first i have $schedules:
$schedules = [{"id":19},{"id":18},{"id":15}]
And the foreach loop is like this:
$queues= [];
foreach ($schedules as $schedule) {
$queues[] = Queue::withTrashed()
->latest()
->where('schedule_id', $schedule);
}
return $queues;
when i return queues it's showing :
Object of class Illuminate\Database\Eloquent\Builder could not be converted to string
The error that shows is related to you are not running the query, you need a ->get() at the end of Queue::...->where(...)->get() to do it.
if you dont do it, as Dhananjay Kyada say in his answer:
it will try to return a query object
But to return a response:
The Response content must be a string or object implementing __toString()
Next, we need to tackle one more thing.
If you are defining the variable $schedules and assigning it the value as it is shown in the question:
$schedules = [{"id":19},{"id":18},{"id":15}]
try to do it taking the JSON as string and converting it into a PHP variable with json_decode:
$schedules = json_decode('[{"id":19},{"id":18},{"id":15}]');
Then you can use the id values in you where clause:
->where('schedule_id', $schedule->id)->get()
Maybe because you are not getting the result from your query. Because it is just a query it will return a query object. You need to add ->get() in order to get the result. You can try the following code:
$queues = [];
foreach ($schedules as $schedule) {
$queues[] = Queue::withTrashed()
->latest()
->where('schedule_id', $schedule)->get()->toArray();
}
return $queues;
I'm trying to send an email to multiple emails, so I did a query to my users tables but the result is an array with keys that don't work mail->to().
I need an array like this: $owners = ['myoneemail#esomething.com', 'myother#esomething.com','myother2#esomething.com']; from database.
My query:
$owners = DB::table('users')->select('email')->where('active', 1)->where('userType', 1)->get();
I also try use ->toArray() but comes with keys.
Email:
Mail::send('email-view', $data, function($message) use ($data, $owners)
{
$message->from('no-reply#email.pt' , 'FROM');
$message->to($owners)->subject('subject');
});
$owners = DB::table('users')->where('active', 1)->where('userType', 1)->pluck('email')->toArray();
You can use ->pluck(), like this:
$owners = DB::table('users')->select('email')->where('active', 1)->where('userType', 1)->get();
$emailList = $owners->pluck('email');
$owners = DB::table('users')->where('active', 1)->where('userType', 1)->pluck('email');
or
$owners = User::where('active', 1)->where('userType', 1)->pluck('email');
here User is your model name
First of all, the where condition is not proper in your query builder code.
It has to be like:
$query->where([
['column_1', '=', 'value_1'],
['column_2', '<>', 'value_2'],
[COLUMN, OPERATOR, VALUE],
...
])
You can use pluck() to get the list in Laravel 5.
All collections also serve as iterators, allowing you to loop over them as if they were simple PHP arrays:
foreach ($owners as $owner) {
echo $owner->filed_name;
echo $owner->filed_name;
...
}
There is no restriction for using the core PHP code while using a PHP framework. You may refer the official PHP Arrays Manual page to work with the language construct.
If you need to convert JSON to array, use:
json_decode($owners);
This is my Laravel controller code
public function switchInfo($prisw, $secsw){
$cur_sw_pair_id = DB::table('sw_pairs')
->select('sw_pair_id')
->where('pri_sw','=',$prisw)
->where('sec_sw','=',$secsw)
->get();
$infolist = DB::table('cust_sw_pair')
->select('interface','pri_sw_vlan','sec_sw_vlan','pri_sw_admin_status','sec_sw_admin_status','description')
->where('sw_pair_id', '=', $cur_sw_pair_id)
->get();
return view('switchinfo.switchinfoview',compact('infolist'));
}
when this code executing it gives Object of class stdClass could not be converted to string error. How can i solve this? How can i pass my infolist into switchinfoview view without getting this error?
You can use pluck() to get value of a column.
Your first query should like this:
$cur_sw_pair_id = DB::table('sw_pairs')
->where('pri_sw','=',$prisw)
->where('sec_sw','=',$secsw)
->pluck('sw_pairs');
Keep the second query as it is.
Hope it will help.
The issue is that ->get() returns a collection, which is a 0-indexed collection of results (rows) from the database. In your case, you want to be using the following query:
$cur_sw_pair_id = DB::table('sw_pairs')
->select('sw_pair_id')
->where('pri_sw','=',$prisw)
->where('sec_sw','=',$secsw)
->first();
And then accessing the property sw_pair_id of $cur_sw_pair_id, like so:
$infolist = DB::table('cust_sw_pair')
->select('interface','pri_sw_vlan','sec_sw_vlan','pri_sw_admin_status','sec_sw_admin_status','description')
->where('sw_pair_id', '=', $cur_sw_pair_id->sw_pair_id)
->first();
Then, in your view, you can access all the properties (anything in the ->select() statement) of $infolist using $infolist->PROPERTY_HERE
Note that using ->first() is essentially using the same as ->get();, but you have to access the results of ->get() using an index, so
$cur_sw_pair_id[0]->sw_pair_id
Hope that provides some insight for you.
I have a controller where I want to combine data from multiple tables with parallel structures. What I want to end up with in the end is one object I can return from the controller so I can parse it in Backbone.
I want to do something like this:
public function index()
{
$mc = MainContact::where('verified', '=', '1')->get();
$sm = SendMessage::where('verified', '=', '1')->get();
$obj = (object) array_merge((array) $mc, (array) $sm);
return $obj;
}
I'm told by another post on StackOverflow that this works in PHP 5.3+. However, this returns the following error in Laravel:
UnexpectedValueException: The Response content must be a string or object implementing
__toString(), "object" given.
How do I implement this method in Laravel? Both $mc and sm return valid objects in Laravel.
Nowadays you can use
$new_collection = $collection->merge($other_collection).
This works in Laravel 4 and seems to handle both arrays and collections.
What you can do here is merge the arrays of the two query result and then use the Response with json output like shown below.
$array = array_merge($mc->toArray(), $sm->toArray());
return Response::json($array);
We can use collection as below
$admins = User::where('type', '=', 'admin')->get();
$authors = User::where('type', '=', 'author')->get();
$admin_author_collection = $admins->merge($authors);
Also, Please refer the various collection methods to below link
http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html
Route::get('test', function(){
$rank = Rank::get();
$policy = Policy::get();
$obj = (object)array_merge_recursive((array)$rank , (array)$policy);
var_dump($obj);
});
This is working for me. Instead of array_merge use array_merge_recursive().
You could simply use array_merge(firstObject,secondObject) function.
$obj = array_merge($mc, $sm);
return $obj;