Laravel Eloquent model JSON output format - json

my problem is about the JSON format I recieve when sending a query to the database.
The output I want:
[{"errors":[{"something":"something"}],"created_at":"2020-10-20 10:10:10","name":"something","id":99}]
I get :
[{"id":99,"name":"something","device_results":[{"devices_id":99,"created_at":"2020-10-20 10:10:10","errors":[{"something":"something"}]}]}]
Which I get with:
public function errors()
{
$errors = DB::table('devices')
->join('device_results', 'devices.id', '=', 'device_results.devices_id')
->select('errors', 'created_at', 'name', 'device_results.id')
->orderBy('created_at', 'desc')
->whereJsonLength('errors', '>', 0)
->get();
return $errors;
}
I would like to get the same results with using my model because if I do this:
public function errors()
{
$devices = Devices::with(['device_results' => function($query) {
$query->select('device_results.devices_id','created_at','errors')
->whereJsonLength('errors', '>', 0)
->orderBy('created_at', 'desc')
->get();
}])->get();
return $devices;
}
Is it always in this format or can I use the model and get the same format as with the DB class? I am using Vue for the front end and would like to avoid nesting.
Thank you

Have you tried to create a Resource ?
The doc : https://laravel.com/docs/8.x/eloquent-resources

Related

Why 'where' return all data in laravel

I am applying search filter in my project so first of all I get data from multiple tables and store in two different variables and then merge these two variable into one so I can filter data from that merged variable. So my code is like that
$data1=Model::query()
->Join('...')
->leftJoin('...')
->where('id',login_user)
->select(...)
->whereRaw('id IN (select MAX(id) FROM table GROUP BY name)')
->groupBy('name')
->get();
$data2=Model2::query()
->leftJoin(...)
->select(...)
->where('id',login_user)
->whereNotIn(..)
->get();
both data1 and data2 return same column with different values so I merge both variable like that
$results = $data1->concat($data2);
No when I already get data so now I need to add filter data from $results so i make post method for that .
so When user request to filter data with name I write query like that
if ($request->name!="") {
$results->when(request('name'), function($q){
$q->Where('name', request('name'));
});
}
$records = $results;
return response()->json(['success'=>true,'message'=>'success', 'data' => $records]);
But that query is not filtering the data and return me all data.I am new in laravel so I don't know what I have done wrong in that any favour will be helpful for me ,thanks.
if (request()->has('name')) {
$results->when(request()->get('name'), function($q){
return $q->where('name', request()->get('name'));
});
}
$records = $results;
return response()->json(['success'=>true,'message'=>'success', 'data' => $records]);
As you use 'when()', you can drop the if expression all together:
$results->when(request()->has('name'), function($q){
return $q->where('name', request()->get('name'));
});
$records = $results;
return response()->json(['success'=>true,'message'=>'success', 'data' => $records]);
request() is a Laravel helper for Request $request
Edit: the where() clause in the ORM is with a small 'w', not 'W' as in orWhere

Raw query to Laravel Query

Raw query to Laravel Query
SELECT * FROM plans_subscriptions WHERE starts_on BETWEEN "2019-07-30" AND "2019-07-26" or expires_on BETWEEN "2019-07-20" AND "2019-07-22"
If you want object response then use this :
PlansSubscriptions::whereBetween('starts_on', ["2019-07-30", "2019-07-26"]);
->orWhereBetween('expires_on', ["2019-07-20", "2019-07-22"]);
->get();
If you want array response then use this :
PlansSubscriptions::whereBetween('starts_on', ["2019-07-30", "2019-07-26"]);
->orWhereBetween('expires_on', ["2019-07-20", "2019-07-22"]);
->get()->toArray();
We can format the date like this :
$start = date("Y-m-d",strtotime($request->input('from_date')));
$end = date("Y-m-d",strtotime($request->input('to_date')));
and use that variable in query like this:
PlansSubscriptions::whereBetween('starts_on', [$start, $end]);
->orWhereBetween('expires_on', ["2019-07-20", "2019-07-22"]);
->get()->toArray();
PlansSubscriptions::whereBetween('starts_on', ["2019-07-30", "2019-07-26"]);
->orWhereBetween('expires_on', ["2019-07-20", "2019-07-22"]);
->get();
Check this,
$users = DB::table('plans_subscriptions')
->where(function ($query){
$query->whereBetween('starts_on', ['2019-07-30', '2019-07-26'])
->orWhereBetween('starts_on', ['2019-07-20', '2019-07-22']);
})
->get();

Use variable on the mysql like sentence on laravel query builder

$key was a variable can be empty or something.
var key='"<?php echo $_REQUEST['key']; ?>"';
then send to the ajax by data
"ajax": {
"url": "{{asset("try")}}",
"type": 'POST',
"dataType": 'json',
"async": true,
"data": {
key : key,
},
}
the try Controller
public function try(Request $request){
$key=$request->key;
DB::query()
->select('A.id','A.upper_p_id','A.key')
->from('users as A')
->leftjoin('products as B', function($join) {
$join->on('A.ID', '=', 'B.p_id');
})
->groupBy('A.id','A.upper_p_id','A.key')
->where('A.key', 'LIKE', '%'.$key.'%');
->get()
return $result;
}
I got the error expression from the queries debug tool?
LIKE '%\"\"%'
But if I use
->where('A.n_geography','LIKE', '%'.''.'%');
It is right sentence from the queries debug tool.
LIKE '%%'
Well - you did put in the double quotes in the key variable...
So it's doing it correctly :-)
If you are trying to get key from request, you ideally should no use $_GET o $_POST.
public function getData(Request $request){
$key = $request->key;
$records = DB::table('users')
->leftJoin('products', 'users.id', '=', 'products.p_id')
->groupBy('users.id','users.upper_p_id','users.key')
->where('users.key', 'LIKE', '%'.$key.'%')
->select('users.id','users.upper_p_id','users.key')
->get();
return response()->json($records, 200);
}
However if the key variable is a javascript variable, then you can not directly use in controller. You need to pass it somehow in route param or using ajax request.
Secondly if you can add conditional when that if $key is present then only do a where clause :
public function getData(Request $request){
$key = $request->key;
$records = DB::table('users')
->leftJoin('products', 'users.id', '=', 'products.p_id')
->groupBy('users.id','users.upper_p_id','users.key')
->when($key, function($q) use($key){
return $q->where('users.key', 'LIKE', '%'.$key.'%');
})
->select('users.id','users.upper_p_id','users.key')
->get();
return response()->json($records, 200);
}
You're double quoting key. The suggested way to share PHP variables as JS variables is to JSON encode them for example:
var key= {!! json_encode(request()->input('key')) !!};
Note that there are no additional quotes necessary in the JS code because valid JSON is also a valid JS variable.
Also note that since you are using Laravel it is recommended you use blade markup and the request() helper for accessing the request parameters
In order to prevent SQL injection it is better not to concatenate the value directly but pass it as a param so try this:
$key = $request->key;
...
->whereRaw('A.key like ?', ['%' . $key . '%']);
And in your JS:
var key='<?php echo $_REQUEST['key']; ?>';

Laravel 5 create pagination from json data in blade view

I have done the query below, and I am able to get the json data from console log, my question is how to make a pagination link using the json data?
$viewData = DB::table('tbl_contents')
->where('record_type', '=', 'Event')
->where('status', '=', 1)
->paginate(3);
return json_encode($viewData);
You may also return the pagination link, see my code below:
$viewData = DB::table('tbl_contents')
->where('record_type', '=', 'Event')
->where('status', '=', 1)
->paginate(3);
return [
'items' => json_encode($viewData),
'pagination_link' => $viewData->links()
];

Yii framework 2.0 pass parameter to eager loading relational database table

Working with Yii framework 2.0 I tried to retrieve data from my relational database tables following the documentation here http://www.yiiframework.com/doc-2.0/guide-db-active-record.html
Below is the code sample under the section Lazy and Eager Loading.
$customers = Customer::find()->limit(100)->with([
'orders' => function($query) {
$query->andWhere('subtotal>100');
},
])->all();
In my case I want to pass a parameter to the andWhere() method as following.
$param = 'something flexible';
$customers = Customer::find()->limit(100)->with([
'orders' => function($query) {
$query->andWhere('subtotal > ' . $param);
},
])->all();
It does not work this way. What do I miss or how can I pass the parameter from the first line to the andWhere() method?
I found the solution as following.
$param = 'something flexible';
$customers = Customer::find()->limit(100)->with([
'orders' => function($query) use($param) {
$query->andWhere('subtotal > ' . $param);
},
])->all();