Actually the scenario is my queries are running on the basis of if
condition. In first scenario
if ($a != "") {
$getData = DB::table('students')->where([
['code', '=', '1'],
['class', '!=', 'General'],
['gender', '=', 'm']
]);
}
> //second scenario
if ($b != '') {
$queryData = $getData->where(ST_Distancesphere(geom, ST_SetSRID(ST_MakePoint($longt, $latt), 4326)), '<', $b)->get();
} else {
$queryData = $getData->get();
}
return $queryData;
in first scenario query is working fine but when $b is not equal to
blank then where condition is not working
It seems you want to use ST_Distancesphere method, you need to use the raw sql.
So if you use whereRaw() like this, and set binding for preventing SQL Injection:
$queryData=$getData->whereRaw("ST_Distancesphere(geom, ST_SetSRID(ST_MakePoint(:lng,:lat), 4326)) < :b", ["lng" => $longt, "lat" => $latt, "b" => $b])
->get();
However, you have different bindings' way before this query,
DB::table('students')->where([['code', '=', '1'],['class', '!=', 'General'],['gender','=', 'm']])
Laravel will get Invalid parameter number error.
So I think you need to change the previous bindings, make them all use same bindings' way:
if($a != "") {
$getData = DB::table('students')
->whereRaw("code = :code AND class != :class AND gender = :gender", ["code" => 1, "class" => "General", "gender" => "m"]);
}
if($b != '') {
$queryData=$getData->whereRaw(" ST_Distancesphere(geom,ST_SetSRID(ST_MakePoint(:longt, :latt), 4326)) < :b", ["longt" => $longt, "latt" => $latt, "b" => $b])->get();
} else {
$queryData=$getData->get();
}
return $queryData;
follow official documentation
https://laravel.com/docs/5.8/queries#conditional-clauses
Related
My Code is like below.
$prayers = Prayer_time::where('mosque_id', $request->mosque_id)
->where('month', $month)
->where('date', $date)
->first();
foreach ($prayers as $key => $prayer) {
if ($prayer != null) {
$payer_times[$key] = $prayer;
}
}
return response()->json(['prayer_times' => $payer_times], 200);
I am getting below output.
{
"prayer_times": {
"incrementing": true,
"exists": true,
"timestamps": true
}
}
How can I iterate through result?
Assuming that first one is an API Controller and you want to iterate over the prayer_times in a frontend
res.data.prayers_time.each({
DO WHATEVER
})
I have a laravel collection that's like this:
$loan = Loans::where([
['OL_TEMP_APP_NO', $appNo]
])
->get();
The $loan collection returns principal, terms, code. The code corresponds to a string. Example 1 = new, 2 = processing, 3 = approved.
How do I parse the values under code before sending them to the view?
You can use CASE WHEN to convert the integer to string code:
$loan = Loans::where([
['OL_TEMP_APP_NO', $appNo]
])
->select('principal', 'terms', DB::raw("
(CASE code
WHEN 2 THEN 'processing'
WHEN 3 THEN 'approved'
ELSE 'new' END) AS code
"))
->get();
if you already know the value of code, or code will always have some fixed values, then you can use like following:
public function getAll(){
// ...
$loans = Loans::where([['OL_TEMP_APP_NO', $appNo]])->get();
$data = [];
foreach($loans as $loan){
$code = Code::getValue($loan->code);
$data[] = [
'principal' => $loan->principal,
'terms' => $loan->terms,
'code' => ($loan->code == 1) ? 'new' : ( ($loan->code == 2) ? 'processing' : 'approved')
]
}
return $data;
}
I want to add models from one table called "modellist" in middle of the program.
foreach ($trans_infos as $key => $trans_info) {
if($trans_info->heirarchy_type==1 || $trans_info->heirarchy_type==2){
$model=TransactionModules::where('id',$info->module_id)->first();
$model_name=$model->model; // here am getting model name form table
use App\Models\.$model_name; //i used this function to include model on middle of program
$model_name::find($info->transaction_id)->update(['status' => 7]);
}
}
I have not tested this but try:
foreach ($trans_infos as $key => $trans_info) {
if($trans_info->heirarchy_type==1 || $trans_info->heirarchy_type==2){
$model=TransactionModules::where('id',$info->module_id)->first();
($model::class)::find($info->transaction_id)->update(['status' => 7]);
}
}
The class method returns the namespace with model name
I hope this works
You can do this direct on eloquent.
no need to declare use first
remember to use namespace as a string => "App\Models\\"
foreach ($trans_infos as $key => $trans_info) {
if($trans_info->heirarchy_type==1 || $trans_info->heirarchy_type==2)
{
$model=TransactionModules::where('id',$info->module_id)->first();
"App\Models\\".$model->model::find($info->transaction_id)
->update(['status' => 7]);
}
}
I have a search function with multiple parameters who seems to not work everytimes on each params for exemple i tested the search query with one param "etat_paiement = 0 ",
normaly i should have no results but i still have one but in the database this record have etat_paiement = 1
where i made a mistake ? thanks a lot in advance
here the code :
$query = EngagementOrder::query();
$filters = [
'structure_engagement_id' => 'structure_id',
'saison_id' => 'saison_id',
'etat_paiement' => 'etat_paiement',
'bl_comptabilite' => 'bl_comptabilite',
];
foreach ($filters as $key => $column) {
$query->when($request->{$key}, function ($query, $value) use ($column) {
$query->where($column, $value);
});
}
$engagements = $query->paginate(10);
in my debug bar i have the query like :
select * from engagement_order limit 10 offset 0
but i run the search with the url like :
https://mydomaine/engagements?etat_paiement=0
UPDATE : here my select box :
{!! Form::select('etat_paiement', array('1' => 'Facture Réglée' , '0' => 'Facture Non Rélgée') , null , ['class' => 'form-control select2 ', 'placeholder' => 'Selectionnez un type de réglement']) !!}
The problem is with the laravel's when method. When you are passing "0" as the first argument to the when function, the below is invoked with the value as "0", which is resolving to be false in this condition: if ($value)
public function when($value, $callback, $default = null)
{
if ($value) {
return $callback($this, $value) ?: $this;
} elseif ($default) {
return $default($this, $value) ?: $this;
}
return $this;
}
Instead of using when, you can generate the query like this:
foreach ($filters as $key => $column) {
if ($request->has($key)) {
$query->where($column, $request->{$key});
}
}
If you want to use when, change your code to
foreach ($filters as $key => $column) {
$query->when($request->has($key), function ($query, $value) use ($column,$key, $request) {
$query->where($column, $request->$key);
});
}
You may try exists instead of $request->{$key} for example:
$request->exists($key)
In your case $request->{$key} is evaluating to false because etat_paiement=0 has a falsy value. On the other hand, the exists will check if the query parameter/$key is present regardless of the value.
when i use following method and pass body key as fail (non defined key) and some value getting pass message in return and empty row gets inserted in table, How do I validate?
Function that I use in REST API,
function categories_POST() {
$title = $this->post('title');
$no = $this->post('no');
$id= $this->post('id');
$this->load->model('model_check');
$msg = $this->model_check->addDetails($title , $no , $id);
$this->response($msg);
}
My model,
function addDetails($x, $y, $z) {
$check = "INSERT INTO categories (title,no,id) VALUES ('$x','$y','$z')";
$query = $this->db->query($check);
if($this->db->affected_rows() > 0) {
return "pass";
} else {
return "fail";
}
}
quite honestly, you'd be better off using the query builder and (depending on what style you follow(fat/skinny controllers/models)) letting the model deal with $this->post() for processing.
Is this Phil Sturgeons/Chris A's rest server?
Something like:
function categories_post() { // doesn't need to be POST()
$this->load->model('model_check');
$msg = $this->model_check->addDetails()
if ($msg)
{
$this->response([
'status' => TRUE,
'message' => 'pass'
], REST_Controller::OK);
}
// default to fail
$this->response([
'status' => FALSE,
'message' => 'fail'
], REST_Controller::HTTP_BAD_REQUEST);
}
Your model,
function addDetails() {
// this only checks to see if they exist
if (!$this->post() || !$this->post('x') || !$this->post('y') || !$this->post('z')) {
return false;
};
$insert = array(
'x' => $this->post('x'),
'y' => $this->post('y'),
'z' => $this->post('z'),
);
if($this->db->insert('categories', $insert))
{
return true;
}
return false; // defaults to false should the db be down
}
IF you mean form_validation you can use this instead of the above.
function addDetails() {
$this->load->library('form_validation');
$this->form_validation->set_rules('x', 'X', 'required');
$this->form_validation->set_rules('y', 'Y', 'required');
$this->form_validation->set_rules('z', 'Z', 'required');
if ($this->form_validation->run() == true)
{
$insert = array(
'x' => $this->post('x'),
'y' => $this->post('y'),
'z' => $this->post('z'),
);
if($this->db->insert('categories', $insert))
{
return true;
}
}
return false; // defaults to false should the db be down
}
This is quite verbose, there's shorter ways to do it, but I'd rather make it easy to figure out.
Two ways of get post values in CodeIgniter
$title = $this->input->post('title');
$no = $this->input->post('no');
$id= $this->input->post('id');
$this->load->model('model_check');
$msg = $this->model_check->addDetails($title , $no , $id);
$this->response($msg);
or
extract($_POST);
Then direct access post name
$this->load->model('model_check');
$msg = $this->model_check->addDetails($title , $no , $id);
$this->response($msg);
Best way is directly access post values in model files (not in controller)
Don't need the pass the POST values in model function.
If you have more queries, then ask to me