how to use json_encode to fetch data from database - php

I Have 2 table that I want to join them and fetch some data like this
I have one student with multiple grade
{
"student": {
"studentID": "2",
"Name": "s1",
"age": " 12",
"grade": [
{
"GradeID": "2"
},{
"GradeID": "3"
}
]
}
I fetch this data from two query in a function in my model and then use json_encode in my controller for my output
but I have this
{
"student": {
"studentID": "2",
"Name": "s1",
"age": " 12"
},
"grade": [
{
"GradeID": "2"
},{
"GradeID": "3"
}
]
}
and now I don't know how to use json_encode for the first format.
thanks
my model(student):
function get_student_id($id)
{
$student['student']=
$this->db->select('tbl_student.*')
->from('tbl_student')
->where('tbl_student.SID',$id)
->get()->row();
$student['grade']=
$this->db->select('tbl_grade.GradeID')
->from('tbl_grade')
->join('tbl_sudent','tbl_grade.StudentID=tbl_sudent.SID')
->where('tbl_student.SID',$id)
->get()->result();
return $student;
}
my controller:
public function get_student_id()
{
$id = $input['one'];
$this->load->model('student');
$temp=$this->student->get_student_id($id);
$output= json_encode($temp);
die($output);
}

You just have to structure the array you're returning from the model correctly. You're putting everything inside two subarrays called student and grade, which are inside the outer array student. Try this:
my model(student):
function get_student_id($id)
{
$student=
$this->db->select('tbl_student.*')
->from('tbl_student')
->where('tbl_student.SID',$id)
->get()->row();
$student['grade']=
$this->db->select('tbl_grade.GradeID')
->from('tbl_grade')
->join('tbl_sudent','tbl_grade.StudentID=tbl_sudent.SID')
->where('tbl_student.SID',$id)
->get()->result();
return $student;
}
I'm not totally certain you want to call get->row() on the first query, if that doesn't work try get->row_array()

Related

Laravel - Modify Fetched Data With Pagination

I want to format some column fetched from database but didn't know how. I use Laravel 8.x. Here's the snippet :
GarageController.php
$q = Garage::with('relative')->paginate(15);
return response()->json($q);
the output
{
"data": [
{
"id": 39819,
"name": "john",
"date": "2020-12-20", // i want to format this with date_format()
"relative": {
"rid": 912039,
"rname": "ROV" // and i just want this value instead of all columns
}
},
{
"id": 38178,
"name": "danny",
"date": "2020-12-20", // and this too
"relative": {
"rid": 182738,
"rname": "YIV"
}
}
],
"links": {
.....
},
"meta": {
....
}
}
The model, the garage have is belong to relative (relative could have many garage).
public function relative() {
return $this->belongsTo(Relative::class, 'relative', 'rid');
}
I tried accessor, but it didn't change anything
public function getDateAttributes($value) {
return date_format(date_create($value), 'd/m/Y');
}
Any help would be appreciated. Thank you.
I think you just need to remove s from the getDateAttributes
From
public function getDateAttributes($value) {
return date_format(date_create($value), 'd/m/Y');
}
To
public function getDateAttribute($value) {
return date_format(date_create($value), 'd/m/Y');
}

Filter relationship, based on array of integers

My model has many options, multiple fields of a single option store values as an array on integers.
I want to filter based on an integer is included.
in php similare to in_array(), but the array is stored in db, and the number is key word.
$productsWithOptions = [
{
"id":2,
"name":"mac 2",
"options":[
{
"id":4,
"price":99.9,
"product_id":2,
"colors":"[4,3,2]",
"sizes":"[5,3,2]"
},
{
"id":5,
"price":99.9,
"product_id":2,
"colors":"[4,4,5]",
"sizes":"[1,2,2]"
},
{
"id":7,
"name":"mac 7",
"options":[
{
"id":19,
"price":99.9,
"product_id":7,
"colors":"[6,3,4]",
"sizes":"[5,2,5]"
},
{
"id":20,
"price":1999.9,
"product_id":7,
"colors":"[1,6,6]",
"sizes":"[5,6,2]"
},
{
"id":21,
"price":1999.9,
"product_id":7,
"colors":"[4,6,5]",
"sizes":"[5,2,2]"
}
]
}
]
$products = Product::whereHas('options', function (Builder $query) use ($arr) {
$query->where('colors','like', "%2%" );
})->get();
This is how options table looks like in db.

Laravel use function in query

In controller get data from db like this, I want to pass whole of $request to another function in this controller to get price it calculating price based of many things from $request:
$user = Auth::user();
$query = Post::query();
$query
->where('province', '=', $user->province)
->where('city', '=', $user->city);
$customers = $query->get();
$customers['calculator'] = $this->calculator($request); // call function
my problem is it return like this:
{
"0": {
"id": 1,
"hash": "RqH29tkfm1dwGrXp4ZCV",
},
"1": {
"id": 3,
"hash": "RqH29tkfm1dwGsXp4ZCV",
},
"calculator": {
"price": 1
}
}
But I need to use that function for each data, and result should be like this:
{
"0": {
"id": 1,
"hash": "RqH29tkfm1dwGrXp4ZCV",
"calculator": {
"price": 1
}
},
"1": {
"id": 3,
"hash": "RqH29tkfm1dwGsXp4ZCV",
"calculator": {
"price": 1
}
}
}
What you want is to set a calculator key for each item in the $customers collection. So you need to loop over it:
foreach ($customers as $customer) {
$customer->calculator = $this->calculator($request);
}
Notice that since the $customer is a Model you should set the calculator as a property. Internally it will be set to the attributes array.

Add extra key in laravel eloquent result

I have a laravel query builder result that looks like this
{
"data": [
{
"id": "",
"awardID": 2,
"title": "Dummy title",
"status": "active",
"raceStart":"",
"raceEnd:":""
}
]
}
What i want to output is something like this
{
"data": [
{
"id": "",
"awardID": 2,
"title": "Dummy title",
"status": "active",
"period": {
"raceStart":"",
"raceEnd:":""
}
}
]
}
This would have been much easier if the period was a table with a 1 to 1 relationship with parent table but this is not the case here.
How can this be achieved?
Check if this will work. I haven't tried though but according to documentation we can add accessor and mutators. But it will change every response you are doing with the model.
Using Eloquent
// Your Model
class Race extends Model
{
{...}
protected $appends = ['period'];
// accessor
public function getPeriodAttribute($value)
{
$this->attributes['period'] = (object)[];
$this->attributes['period']['raceStart'] = $this->attributes['raceStart'];
$this->attributes['period']['raceEnd'] = $this->attributes['raceEnd'];
unset($this->attributes['raceStart']); = $value;
unset($this->attributes['raceEnd']);
return $this->attributes['period'];
}
}
Now when you will access $race->period will give the raceStart and raceEnd value.
Ref: https://laravel.com/docs/5.4/eloquent-mutators#accessors-and-mutators
else another option is after query, do a map
{...}
->map(function($data) {
$data->period = (object)[];
$data->period['raceStart'] = $data->raceStart;
$data->period['raceEnd'] = $data->raceEnd;
unset($data->raceStart);
unset($data->raceEnd);
return $data;
});
Ref: https://laravel.com/docs/5.4/eloquent-collections#introduction
Using QueryBuilder
$races = DB::table('races')->get();
$races = array_map(function ($data) {
$data->period = (object)[
"raceStart" => $data->raceStart,
"raceEnd" => $data->raceEnd
];
unset($data->raceStart);
unset($data->raceEnd);
return $data;
}, $races->data);

Laravel Eloquent - how to join a table

I working on an API for my app.
I'm trying to pull items from the database and return them in JSON object,
my items table looks like this:
Items
-id
-name
-description
-price
-currency_id
-company_id
this is how I'm getting the items:
$rows = Company::where('guid',$guid)
->first()
->items()
->orderBy('name', $sort_order);
I want to replace the currency_id with a currency object that contains all the columns of currency table
so my result will be like this:
[
{
'id':'1',
'name':'name',
'description': 'example',
'price':'100',
'currency':{
'id':'1',
'name':'usd',
'symbol': '$'
}
}
]
update:
This is my currencies table:
id
name
symbol
code
Edit 2: The user's problem was more complex than this since there was pagination and search integration with the query. Helped with https://pastebin.com/ppRH3eyx
Edit : I've tested the code. So here.
In Company model
public function items()
{
return $this->hasMany(Item::class);
}
In Item model
public function currency()
{
return $this->belongsTo(Currency::class);
}
Controller logic
$items = Company::with(['items' => function($query) use ($sort_order) {
$query->with('currency')->orderBy('name', $sort_order);
}])
->where('guid', $guid)
->first()
->items;
Result with test data
[
{
"id": 2,
"name": "Toy",
"description": "Random text 2",
"price": 150,
"company_id": 1,
"currency_id": 1,
"currency": {
"id": 1,
"name": "usd",
"symbol": "$",
"code": "USD"
}
},
{
"id": 1,
"name": "Phone",
"description": "Random text",
"price": 100,
"company_id": 1,
"currency_id": 1,
"currency": {
"id": 1,
"name": "usd",
"symbol": "$",
"code": "USD"
}
}
]
Try this.
$rows = Company::with('items.currency')
->where('guid', $guid)
->first()
->items()
->orderBy('name', $sort_order);
Try below
Make one relationship in Item Model
public function currencies() {
return $this->hasMany('App\Currency');
}
then do below in your controller
$row=Items::All()->with('currencies');

Categories