I have this variable called $result = $request->data;
when I use something like this return $result; I can get sample output like this
["WLP001","WLP002","WLP003"]
I'm trying to use these values on whereIn function of laravel
Code
public function get_compare_data( Request $request ){
$result = $request->data;
$data = YeastModuleModel::whereIn('part_number', [$result])->get();
return $data;
}
But I'm getting internal server error 500
According to Laravel docs, https://laravel.com/docs/8.x/queries
The whereIn method verifies that a given column's value is contained within the given array.
$result is an array.
you should not put $result in another array.
$users = DB::table('users')
->whereIn('id', [1, 2, 3])
->get();
so you should change your code to:
public function get_compare_data( Request $request ){
$result = $request->data;
$data = YeastModuleModel::whereIn('part_number', $result)->get();
return $data;
}
Related
I am building an API with laravel, so I am trying to pass Laravel's Eloquent functions as string and execute them in the controller, actually I am sending a JSON object but I am converting it to a string in backend, here is what I tried to do
API URL with parameters:
http://www.example.com/api/articles?parameters={"orderByDesc":"'created_at'", "limit":"2"}
Controller side:
$json = json_decode(request('parameters'), TRUE);
$query = '';
foreach ($json as $function => $value){
$query .= $function.'('.$value.')->';
}
$query = $query.'get();';
return $query;
Output:
orderByDesc('created_at')->limit(2)->get();
Now how can I execute this string as code on the model, example:
$articles = Article::orderByDesc('created_at')->limit(2)->get();
I couldn't concatenate like this: Article::.$query
And I can't use PHP's eval()
The idea is to use Laravel's Eloquent functions inside a JSON object and pass them in one URL parameter.
Thanks
Maybe you should try this.
$json = json_decode(request('parameters'), true);
$query = Article::query();
foreach($json as $function => $value){
$query->{$function}($value);
}
$query = $query->get();
return $query;
You can run function on object with ->{$func_name} syntax
Edit: You can pass multiple arguments too. But you can check if whether value is array or not:
foreach($json as $function => $value){
if(is_array($value)) {
$query->{$function}(...$value);
} else {
$query->{$function}($value);
}
}
In this case you can have: {"orderByDesc":"'created_at'", "limit":"2", "where": ["column_name", "LIKE", "%SOME_STRING"]} and it will generate query equivalent to: ->where('column_name', 'LIKE', '%SOME_STRING')
One of the routes I'm making for my API in laravel requires me to pass a variable to a ->each() function.
This can be seen below:
public function by_location($zone_id)
{
$zone = Zone::where('id', $zone_id)->get()[0];
error_log($zone->id);
$exhibitors = Exhibitor::where('zone_id', $zone_id)->get();
$exhibitors->each(function($exhibitor, $zone)
{
error_log($zone->id);
$exhibitor['zone_info'] = $zone;
});
return response()->json($exhibitors);
}
This first error_log outputs '2', but with the second I get 'Trying to get property 'id' of non-object'.
Any help is apprecited!
You probably want to use $zone which you selected from database on first line.
Also if you want to change value of item you are iterating you have to use ->map() instead of ->each()
I changed ->get()[0] to ->first(). Never use ->get()[0]
public function by_location($zone_id)
{
$zone = Zone::where('id', $zone_id)->first();
error_log($zone->id);
$exhibitors = Exhibitor::where('zone_id', $zone_id)->get();
$exhibitors->map(function($exhibitor) use ($zone){
error_log($zone->id);
$exhibitor['zone_info'] = $zone;
return $exhibitor;
});
return response()->json($exhibitors);
}
How to loop the eloquent collection from one to another? I'm just getting first line of array. I have more than 4 array in the collection.
$queries = Students::where('year',"=", 1)->get();
$students = new Students();
foreach ($queries as $query) {
$students->name = $query->name;
$students->faculty = $query->faculty ."Add something";
$students->year = $query->year;
}
dd($students);
I want to change the collection a bit before I print to json. For example, I want add something behind the faculty
Use the transform() method to modify collection:
$students = Students::where('year', 1)->get();
$students->transform(function($i) {
$i->faculty = $i->faculty . 'add something';
return $i;
});
You also can use resource classes to transform the data before returning JSON response.
You could use map() to modify collection-
$queries = $queries->map(function($query){
$query->faculty = $query->faculty."kfjhgli";
return $query;
});
return $queries;
I am using codeigniter and I have made a function to return name of the user. Here is the code:
$this->db->where('u_id', $id);
$query = $this->db->get('users');
$data = $query->result_array();
$string = $data->u_name.' '.$data->u_surname;
return $string;
When I am using this function i get this error:
Message: Trying to get property of non-object and recall the line with
$string = [...]
Use foreach loop:
foreach ($data as $row)
{
echo $string = $data['u_name'].' '.$data['u_surname'];
}
You can try like this.In codeigniter,The row() returns the matched first row according to your condition in object form.
$this->db->where('u_id', $id);
$query = $this->db->get('users');
$data = $query->row();//change here
$string = $data->u_name.' '.$data->u_surname;
//echo $string;
return $string;
for more see Codeigniter Result Sets
Try this code to return
$this->db->select('*');
$this->db->from('users');
$this->db->where(array('u_id'=>$id));
$query=$this->db->get();
if($query->num_rows()()>0)
{
$data = $query->result();
return $data->u_name.' '.$data->u_surname;
}
This is because the function you chose to generate results for you query.
$data = $query->result_array();
result_array() returns the results in an array even if you only had one result, so when you try to $data->u_name for instance, you have this error because the array does not have that property.
You can do a foreach on $data and perform your logic or use other methods to get the result from the query like $query->row_array();
Take a look on the codeigniter documentation: Generating Query Results
I'm trying to build a query based on URL parameters. When the Controller is loaded I need to check which parameters have been provided and build a query from them. It's working with static values, but isn't working with conditional statements. Is my laravel syntax correct?
class OrdenesController extends BaseController {
public function showOrdenes($action)
{
$my_id = Auth::user()->id;
$my_cod = Auth::user()->codprov;
switch ($action)
{
case 'list':
$rows = DB::table('ordens')->count();
if(Input::get("jtSorting"))
{
$search = explode(" ", Input::get("jtSorting"));
$numorden= Input::get("nro_orden");
$filtros =explode(" ", $filtros);
$data = DB::table("ordens")
->select(array('*', DB::raw('SUM(cant_pend) as cant_pend'), DB::raw('SUM(importe) as importe')))
->where('cod_prov', '=', $my_cod)
->where('nro_orden', '=', $numorden)///work
---------- ////no work
if (Input::has('nro_orden')) {
->where('nro_orden', '=', $numorden)
}
---------- /// no work
->groupBy('nro_orden')
->skip(Input::get("jtStartIndex"))
->take(Input::get("jtPageSize"))
->orderBy($search[0], $search[1])
->get();
}
return Response::json(
array(
"Result" => "OK",
"TotalRecordCount" => $rows,
"Records" => $data
)
);
break;
};
}
}
You are missing the variables, no? You haven't told PHP what variable/object to do the where() to in your condition. The magic of Laravel's Eloquent (and a lot of other libraries) is that when you call its methods, it returns itself (the object) back so you can make another method call to it right away.
So when you do this:
$data = DB::table("ordens")
->select(...)
->where(...);
is the same as:
$data = DB::table("ordens");
$data = $data->select(...);
$data = $data->where(...);
But you are trying to do ->where(...) right away after if condition. You need to tell PHP which object/variable you are trying to call the method from. Like this:
$num = Input::get("nro_orden");
$data = DB::table("ordens")
->select(array('*', DB::raw('SUM(cant_pend) as cant_pend'), DB::raw('SUM(importe) as importe')))
->where('cod_prov', '=', $my_cod);
if (Input::has('nro_orden')) {
$data = $data->where('nro_orden', '=', $num);
}
$data = $data->groupBy('nro_orden')
->skip(Input::get("jtStartIndex"))
->take(Input::get("jtPageSize"))
->orderBy($search[0], $search[1])
->get();