Laravel - get DB result without table column name - laravel

I wanted to have the result with only the values not with the table column name in Laravel 4.2. For example,
$recs = DB::table('table_name')
->select('id', 'title')
->get();
the result is
array(2) {
[0]=>
object(stdClass)#863 (2) {
["id"]=>
int(2)
["title"]=>
string(8) "my title"
}
[1]=>
object(stdClass)#862 (2) {
["id"]=>
int(3)
["title"]=>
string(10) "my title 2"
}
}
but I want to have only the result NOT the column name, like
[
2,
"my title"
],
[
3,
"my title 2"
]
yes, I can make it by looping the result and make new array without column name. But is there are any way to get the result in this fashion using Laravel ?

Try
$recs = DB::table('table_name')->pluck('id', 'title');
dd($recs->all());

You can use the map() and the array_values() methods:
$recs->map(function($i) {
return array_values((array)$i);
})
I'm not sure about Laravel 4.2, but I've just tested it and it works perfectly in Laravel 5.3. If it doesn't work in 4.2, use the native array_map() function instead.

Reference
Try $recs->flatten()->all()
Update
Since your $recs looks like an array from your error. Try converting to collection. I hope this will work on v4.2
$recsCollection = new \Illuminate\Database\Eloquent\Collection($recs);
$recsCollection->flatten()->all();

DB::table('table_name')->all()->lists('id', 'title')->toArray()
Referance: Retrieving A List Of Column Values

Related

how to fetch the MySQL data and use it on the controller in CODEIGNITER

I am facing the data from the database as an array and now I want to access the data in the same Controller method. Is it possible?
suppose my MODEL is (method name attendance)
$query = $this->db->query("SELECT emp_name FROM attendance WHERE id= '1' ");
$result = $query->getResult('array');
My controller:
$data["emp_info"]=$this->userdata->attendance();
return view("addleave_v",$data);
So in the controller, I have fetched the data and stored it on $data['emp_info'] it is a single element array. So I want to use the emp_name in the controller. How can I use it? I tried emp_info['emp_name], $data['emp_info']['emp_name']
I have used an image attachment. Thanks
I recommend you to see the library Result Arrays and Result Rows.
Based on the data you provided (var_dump)
array(1) { [0]=> array(10) { ["uiid"]=> string(2) "30"
["attendance_date"]=> string(10) "2021-03-09" ["emp_id"]=> string(1)
"9" ["time_in"]=> string(19) "0000-00-00 00:00:00" ["time_out"]=>
string(19) "0000-00-00 00:00:00" ["comments"]=> string(14) "APPROVED
LEAVE" ["overtime"]=> string(1) "0" ["status1"]=> string(1) "1"
["created_by"]=> string(0) "" ["total_time"]=> string(0) "" } }
Your array is structured as a multi-element array. You can view the current data using a loop (foreach) or refer to the first element of an array (in controller $data["emp_info"][0]['emp_name'] or in view $emp_info[0]['emp_name']).
If you need a single-element array, use getRowArray() or getRow('array'). Then you will be able to use the variables as you first wanted.
in controller $data["emp_info"]['emp_name']
in view $emp_info['emp_name]
I recommend that you try the print_r($emp_info); command in your view(addleave_v). You will see what data structure has been assigned to the variable.

How to get random row in object variable in Laravel?

Sorry for my bad english, I want to get a single row in my object. And I want that in random order. Im using array_rand() and it only return errors as stated below:
ErrorException: array_rand() expects parameter 1 to be array, object given in file C:\xampp\htdocs\user\TestProject\app\Http\Controllers\TestController.php on line
Here is my object.
"my_list": [
{
"id": 1,
"name": "My Name Test",
"address": [
{
"id": 1,
"city": "Manila",
"country": "Philippines"
}
]
},
{
"id": 2,
"name": "Your Name Test",
"address": [
{
"id": 2,
"city": "Cebu",
"country": "Philippines",
}
]
}
]
The problem is I want only to get a single row to the my_list which is object and not an array.
Here is my code.
$course = Course::where('id', 1)->with('my_list')->first();
$random_list = array_rand($course->my_list);
return $random_list;
I also try adding number of row in the array_rand like this.
$random_list = array_rand($course->my_list, 1);
But still not working.
What did I missed?
Any Eloquent query returns, by default, a Collection, even for the underlying relationships. Since you are working with one, this should work:
$course->my_list->random();
This will return only one item. If you want more, you could pass an argument to the random() method specifying the count of items you want.
For more information, check the documentation.
This Object is a Laravel collection. Please refer to the collection documentation.
https://laravel.com/docs/5.7/collections#method-random
You can try $course->my_list->random()
If you still wanna do this with your approach, can you try get_object_vars function to cast object into array.
$array = get_object_vars($object);
so that you can use them as an array in array_rand.
You might get an error, hence that it's an multi-dimensional array. Let me know so i may update.
Update for multidimensional:
Please refer to this.
// The second parameter of json_decode forces parsing into an associative array
$array = json_decode(json_encode($object), true);
try this:
$course = Course::where('id', 1)
->with(['my_list' => function($query) {
$query->inRandomOrder();
}])->first();
return $course->my_list;
Try this method:
$course = Course::where('id', 1)
->with(['my_list' => function($query) {
$query->inRandomOrder()->first();
}])->first();
return $course->my_list;
this method is more efficient since you will only get 1 row from my_list not like when you use $course->my_list->random() which retrieves all data and from there select a random row.
$random_list = $course['my_list']->random(number);
ps: number = number of element you want to get ,

Laravel - Eloquent with select not returning values

I'm having the following problem, I'm using scope in Laravel and I have the following relationship:
Enquiry
pickup_address
dropoff_address
Notes
This is referenced in the model:
public function pickup_address() {
return $this->belongsTo('App\Address', 'pickup_address', 'id');
}
I want to return the enquiry, as well as postcode which is stored in the Address table. I just want this column from this table and I have done the following:
return $query->with(['pickup_address' => function ($query) {
$query->select('postcode');
}])->get();
This gives the following (json):
{
"id":1,
"pickup_address":null
"notes":"hello world",
"created_at":"2017-06-08 09:56:52",
"updated_at":"2017-06-08 09:56:52"
}
This is not giving the postcode and just gives the pickup_address as null. However, removing the $query->select('postcode') gives:
{
"id":1,
"pickup_address": {
"id":140,
"house_number":null,
"address_1":"Address 1",
"address_2":null,
"postcode":"POSTCODE",
"city":"CITY",
"county":"C0UNTY",
"created_at":"2017-06-08 09:56:23",
"updated_at":"2017-06 0}",
"notes":"Hello world","
"created_at":"2017-06-08 09:56:52",
"updated_at":"2017-06-08 09:56:52"
}
However, I'm using Vue and using a table, so I just need the particular field to be returned that matches the column, rather than the entire object being returned.
Can anyone suggest a solution, please? I have followed some examples online and they suggest the $query->select('postcode')

Undefined index in codeigniter session

When I create a new User, I store in session the new e-mail like this:
$this->session->set_userdata('new_user', ['new_email', $data['email']]);
If I use var_dump on $this->session->userdata('new_user'), the result is the following:
array(2) { [0]=> string(9) "new_email" [1]=> string(24) "email#email.com" }
But when I try to access it to print the value, by echoing $this->session->userdata('new_user')['new_email'], an error saying the index new_email does not exist. I've used this way of printing values in my whole website, but specifically in this page, it does not work.
Use $this->session->set_userdata('new_user',$data['email'])

Hide specific columns from pivot key

I have 2 tables say abc and xyz with ManyToMany relationship built over another table say abc_xyz (whose data will be returned as pivot key). However, pivot key upon retrieval has abc_id and xyz_id in return. I am able to access other columns in from abc_xyz table using method withPivot('dummy')
But, I want to hide the abc_id and xyz_id from the response. How do I do that?
I can hide the entire pivot key by using $hidden array but I want to hide only specific columns not the entire key.
Current Response
{
"abc_uuid": "some uuid",
"xyz" : [
{
"xyz_uuid": "some uuid",
"pivot": {
"abc_id": 1,
"xyz_id": 1,
"dummy" : "dummy value"
}
},
{
"xyz_uuid": "some uuid",
"pivot": {
"abc_id": 1,
"xyz_id": 2,
"dummy" : "dummy value"
}
}
]
}
So, I need only dummy from the pivot key, and hide abc_id and xyz_id. How do I do that?
Found a crude way to get this done. Found this answer in laravel issues unable to find the link now. However, it asks me to just add a method in my model and unset the keys I do not want.
public function toArray()
{
$attributes = $this->attributesToArray();
$attributes = array_merge($attributes, $this->relationsToArray());
foreach($attributes['xyz'] as $key => $value) {
unset($value['pivot']['abc_id']);
unset($value['pivot']['xyz_id']);
$attributes['xyz'][$key] = $value;
}
return $attributes;
}
this unsets the unwanted keys from my response. I hope laravel gives out an easy way for this.

Resources