Query in Api Laravel - php

I'm trying to make APIs showing data from two tables, but I'm stuck at this point.
This is my ApiController:
public function postDetaillog(Request $request)
{
$response = array();
$validator = Validator::make(
$request->all(),
[
'id'=> 'required',
]
);
if ($validator->fails()) {
$message = $validator->errors()->all();
$result['api_status'] = 0;
$result['api_message'] = implode(', ',$message);
$res = response()->json($result);
$res->send();
exit;
}
$data = DB::table('log_patrols')
->where('id', $request->input('id'))
->first();
$site = asset("uploads").'/';
$result = DB::table('log_patrol_details')
->select("*",DB::raw("concat('$site',photo1) as photo1"),DB::raw("concat('$site',photo2) as photo2"),DB::raw("concat('$site',photo3) as photo3"))
->where('id', $request->input('id'))
->first();
if (count($result) == 0) {
$response['api_status'] = count($result);
$response['api_message'] = "No data";
} else {
$response['api_status'] = 1;
$response['api_message'] = "success";
$response['data'] = $data;
$response['result'] = $result;
}
return response()->json($response);
}
first table
second table
Whenever I try to get the results, it always gives me 0 = no data
Could you please help me?

If what you get is a collection you may use if ($result->count() == 0) to check if it is empty.
Change as follows:
if ($result->count() == 0) {
$response['api_status'] = 0; // Don't use useless logic
$response['api_message'] = "No data";
} else {
$response['api_status'] = 1;
$response['api_message'] = "success";
$response['data'] = $data;
$response['result'] = $result;
}

Related

filtering and sorting with pagination in laravel

Hi I'm using Laravel and I have a sorting and filtering system it works via url like this
http://localhost:8000/halehule/category/103?type=all&minprice=+10+&maxprice=+10000000000+&color=&sortBy%5Bfield%5D=price&sortBy%5BorderBy%5D=desc
so when I use pagination it does not work and refresh to original page like this :
http://localhost:8000/halehule/category/103?page=2
How can I use pagination with sorting and filtering like this
here is my method
public function brandProduct($shop, $id, Request $request) {
$colors = Color::all();
$shop = Shop::where('english_name', $shop)->first();
$shopTags = $shop->tags;
$shopCategories = $shop->ProductCategories()->get();
$categories = Shop::where('english_name', $shop->english_name)->first()->ProductCategories()->get()->where('parent_id', null);
$brand = Brand::where('id', $id)->get()->first();
$brands = $shop->brands;
$shopProducts = $shop->products;
$minPriceProduct = $shopProducts->min('price');
$maxPriceProduct = $shopProducts->max('price');
//color product and category product merging
if($request->color == null){
$colorAndBrandProducts = $brand->products->sortByDesc('created_at');
}
else{
$colorProducts = Color::where('code', $request->color)->get()->first()->products;
$brandProducts = $brand->products;
$colorAndBrandProducts = collect();
foreach($colorProducts->toBase()->merge($brandProducts)->groupBy('id') as $allProducts){
if($allProducts->count() > 1){
$colorAndBrandProducts[] = $allProducts;
}
}
$colorAndBrandProducts = $colorAndBrandProducts->first();
}
if ($request->has('type') and $request->has('sortBy') and $request->has('minprice') and $request->has('maxprice') and $request->has('color')) {
if($colorAndBrandProducts != null){
$minPrice = $request->minprice;
$maxPrice = $request->maxprice;
$filterBy = $request->type;
$sortBy = $request->sortBy['field'];
$perPage = 16;
if($shop->template->folderName == 2){
$sortBy_array = explode('|', $request->sortBy['field']);
$sortBy = $sortBy_array[0];
$orderBy = $sortBy_array[1];
}
else{
$orderBy = $request->sortBy['orderBy'];
}
if ($request->type == 'all') {
if ($orderBy == 'desc') {
$products = $colorAndBrandProducts->whereBetween('price', [$minPrice, $maxPrice])->sortByDesc($sortBy)->unique('id');
} else {
$products = $colorAndBrandProducts->whereBetween('price', [$minPrice, $maxPrice])->sortBy($sortBy)->unique('id');
}
} else {
if ($orderBy == 'desc') {
$products = $colorAndBrandProducts->where('type', $filterBy)->whereBetween('price', [$minPrice, $maxPrice])->sortByDesc($sortBy)->unique('id');
} else {
$products = $colorAndBrandProducts->where('type', $filterBy)->whereBetween('price', [$minPrice, $maxPrice])->sortBy($sortBy)->unique('id');
}
}
}
else{
$products = collect();
}
}
else {
$products = $colorAndBrandProducts;
}
$total = $products->count();
$perPage = 16; // How many items do you want to display.
$currentPage = request()->page; // The index page.
$productsPaginate = new LengthAwarePaginator($products->forPage($currentPage, $perPage), $total, $perPage, $currentPage);
$template_folderName = $shop->template->folderName;
SEOTools::setTitle($shop->name . ' | ' . $brand->name);
SEOTools::setDescription($shop->description);
SEOTools::opengraph()->addProperty('type', 'website');
return view("app.shop.$template_folderName.layouts.partials.products", compact('products','minPriceProduct', 'maxPriceProduct', 'shopCategories', 'brand', 'shop', 'categories', 'productsPaginate', 'brands', 'shopTags','colors'));
}
I use this method for sorting and filtering and use pagination works great but without sorting and filtering
just apply ->append($_GET) to your pagination

Api Pagination in Symfony

I am working on API, I have a controller that query for results to a framework7 app. (first, last and both). I, however, want to add pagination from API to framework but I have not paginated in Symfony before, what is the best practice?
I tried paginator but there are not many examples of it. Below is my controller function.
public function getEventSessionAttendeeAction(request $request, $eventSessionId)
{
$searchFields = [
'o.email',
'a.email',
'a.firstName',
'a.lastName',
'a.barcode1',
'a.barcode2',
'a.id',
'o.id'
];
/** #var \KCM\ApiBundle\Entity\Api\EventSession $eventSession */
$eventSession = $this->get('doctrine')->getRepository('KCMApiBundle:EventSession')->findOneBy(
[
'id' => $eventSessionId
]
);
/** #var ApiEntity\Event $event */
$event = $eventSession->getEvent();
$childSafe = $event->getChildSafe();
$filter = $request->get('filter');
$match_level = 0;
//Searches by email address
if ( filter_var($filter, FILTER_VALIDATE_EMAIL)) {
$searchFields = [
'a.email'
];
$match_level = 1;
//Searches for first or last name
}elseif(preg_match('/^[a-zA-Z\-]*$/', $filter)){
$searchFields = [
'a.lastName',
'a.firstName'
];
$match_level = 2;
//Searches by barcode
}elseif (preg_match('/^[0-9]+/', $filter)){
if ($childSafe == 2) {
$searchFields = [
'a.barcode3'
];
} else {
$searchFields = [
'a.barcode1'
];
}
$match_level = 4;
}
//Searches for first and last name(must have at least first characters for each
if(preg_match('/^([a-z|A-Z]+)\s{1}([a-z|A-Z]+)/', $filter)){
$match_level = 3;
}elseif (preg_match('/^\s*$/', $filter)){
$match_level = 5;
}
try {
/** #var ApiEntity\EventSession $eventSession */
$em = $this->getDoctrine()->getManager();
$qb = $em->createQueryBuilder();
$qb->select(array('a', 'o'))
->from('KCMApiBundle:EventAttendee', 'a')
->join('a.eventOrder', 'o')
->join('o.event', 'e')
->join('e.eventSessions', 'es')
->where($qb->expr()->andX(
$qb->expr()->eq('es.id', $qb->expr()->literal($eventSessionId))
))
->andWhere('a.sessionCheckedIn = 1');
if ($match_level === 3){
$expr = $qb->expr()->andX();
list($first, $last) = explode(' ', $filter);
$last = $last. '%';
$expr->add($qb->expr()->like('a.lastName', $qb->expr()->literal($last)));
$first = $first. '%';
$expr->add($qb->expr()->like('a.firstName',$qb->expr()->literal($first)));
}elseif ($match_level === 5){
$expr = $qb->expr()->andX();
$paginator = new Paginator($qb);
$paginator->getQuery()
->setFirstResult(0)
->setMaxResults(10);
}else {
$expr = $qb->expr()->orX();
foreach ($searchFields as $field) {
if ($match_level === 1) {
$literalFilter = $filter;
$expr->add($qb->expr()->like($field, $qb->expr()->literal($literalFilter)));
} elseif ($match_level === 2) {
$literalFilter = $filter;
$expr->add($qb->expr()->like($field, $qb->expr()->literal($literalFilter)));
} elseif ($match_level === 4) {
$literalFilter = $filter;
$expr->add($qb->expr()->eq($field, $qb->expr()->literal($literalFilter)));
}
}
}
$qb->andWhere($expr);
$results = $qb->getQuery()->getResult();
if ($results) {
return $this->getApi()->serialize($results);
}
return new Response(null, Response::HTTP_NOT_FOUND);
} catch (\Exception $e) {
$this->get('logger')->error($e->getMessage());
}
}
What I am trying to eventually do is to be able to use this query to paginate to the framework7 app. should I create a new public function to paginate or is there a way to do it within this function?
Did you try to use knppagination bundle?
https://github.com/KnpLabs/KnpPaginatorBundle

Laravel - Import excel keep looping

Dears,
i have an excel file with 5K rows and i'm importing it to my table in the DB successfully.
But the error, when the system finish all the rows, it keeps looping and the page doesn't stop running and not redirecting to my view.
My controller:
if($request->hasFile('import_file')){
$path = $request->file('import_file')->getRealPath();
$data = \Excel::load($path)->get();
foreach ($data as $key => $row) {
$res = policies::where('phone', '=', $row['phone'])
->where('draft_no', '=', $row['draftno'])
->where('due_date', '=', $duedate)
->select('id')->get()->toArray();
if(empty($res)) {
$polic = new policies();
$polic->cust_id = $row['custno'];
$polic->policy = '';
$polic->bord_date = $borddate;
$polic->client_id = $row['clientid'];
$polic->client_no = $row['clientno'];
$polic->client_name = $row['clientname'];
$polic->draft_no = $row['draftno'];
if ($row['status'] == '') {
$polic->status = '';
} else {
$polic->status = $row['status'];
}
$polic->due_date = $duedate;
if ($row['curno'] == 'USD') {
$polic->currency = 1;
} else {
$polic->currency = 0;
}
$polic->amount = $row['amnt'];
$polic->zone = $row['zone'];
$polic->broker_id = $row['brokercode'];
$polic->broker_name = $row['brokername'];
$polic->remarks = $row['remarks'];
$polic->phone = $row['phone'];
$polic->insured_name = $row['insname'];
// $polic->cust_id = $row['valuedate'];
$polic->address = ''; //address
if (trim($row['status']) == 'P') {
$polic->paid_at = date('Y-m-d');
}
$polic->new = 1; //address
$polic->save();
}
else {
//am updating the imported date in the DB
}
what is very strange that in my localhost is working fine, but in digitaloceans cloud, keep looping without redirecting.
Thanks for your help.
I can be because you have 5000 rows to insert and 5000 insert operation consumes lots of memory. What you can try is batch insert operation.
In your policies.php make all fields fillable
protected $fillable=['cust_id ','policy','bord_date','client_id','client_no','client_name ','draft_no','bord_date','status','due_date','currency','amount','zone','broker_id','broker_name','remarks','phone','insured_name','address','paid_at','new'];
And on your excel file import use exists rather than getting collections.
if($request->hasFile('import_file')){
$path = $request->file('import_file')->getRealPath();
$data = \Excel::load($path)->get();
$data=[];
$i=0;
foreach ($data as $key => $row) {
$res = policies::where('phone', '=', $row['phone'])
->where('draft_no', '=', $row['draftno'])
->where('due_date', '=', $duedate)
->exists();
if(!$res) {
$i++;
$data[$i]['cust_id ']=$row['custno'];
$data['policy'] = '';
$data['bord_date'] = $borddate;
$data[$i]['client_id'] = $row['clientid'];
$data[$i]['client_no'] = $row['clientno'];
$data[$i]['client_name'] = $row['clientname'];
$data[$i]['draft_no'] = $row['draftno'];
if ($row['status'] == '') {
$data[$i]['status'] = '';
} else {
$data[$i]['status'] = $row['status'];
}
$data[$i]['due_date'] = $duedate;
if ($row['curno'] == 'USD') {
$data[$i]['currency'] = 1;
} else {
$data[$i]['currency'] = 0;
}
$data[$i]['amount'] = $row['amnt'];
$data[$i]['zone'] = $row['zone'];
$data[$i]['broker_id'] = $row['brokercode'];
$data[$i]['broker_name'] = $row['brokername'];
$data[$i]['remarks'] = $row['remarks'];
$data[$i]['phone'] = $row['phone'];
$data[$i]['insured_name'] = $row['insname'];
// $data[$i]['cust_id'] = $row['valuedate'];
$data[$i]['address'] = ''; //address
if (trim($row['status']) == 'P') {
$data[$i]['paid_at'] = date('Y-m-d');
}
$data[$i]['new'] = 1; //address
}
else {
//am updating the imported date in the DB
}
}
policies::insert($data);

Undefined variable: error in adding field into db

I'm getting error:Undefined variable: error
in my code:
public function add(){
$this->polls_model->rules = Pf::event()->trigger("filter","polls-adding-validation-rule",$this->polls_model->rules);
$template = null;
$template = Pf::event()->trigger("filter","polls-add-template",$template);
if ($this->request->is_post()){
$data = array();
$data["polls_question"] = $this->post->{"polls_question"};
$data["polls_pubdate"] = str_to_mysqldate($this->post->{"polls_pubdate"},$this->polls_model->elements_value["polls_pubdate"],"Y-m-d H:i:s");
$data["polls_unpubdate"] = str_to_mysqldate($this->post->{"polls_unpubdate"},$this->polls_model->elements_value["polls_unpubdate"],"Y-m-d H:i:s");
if (is_array($this->post->{"polls_status"})){
$data["polls_status"] = implode(",",$this->post->{"polls_status"});
}else{
$data["polls_status"] = $this->post->{"polls_status"};
}
$port_answer = isset($this->post->{"answer"}) ? $this->post->{"answer"} : array();
$data = Pf::event()->trigger("filter","polls-post-data",$data);
$data = Pf::event()->trigger("filter","polls-adding-post-data",$data);
$var = array();
$pollq_multiple_yes = intval($this->post->{'pollq_multiple_yes'});
$data['polls_multiple'] = 0;
if ($pollq_multiple_yes == 1) {
if(intval($this->post->{'pollq_multiple'}) > count($port_answer)){
$data['polls_multiple'] = 1;
}else{
$data['polls_multiple'] = intval($this->post->{'pollq_multiple'});
}
} else {
$data['polls_multiple'] = 1;
}
//debug($data);
Pf::database()->query('START TRANSACTION');
$inserted = $this->polls_model->insert($data);
if($inserted === false){
Pf::database()->query('ROLLBACK');
}else{
$new_id = $this->polls_model->insert_id();
$insert_meta = true;
if(count($port_answer) > 0){
$custom = array();
$int = count($port_answer);
for ($i = 0; $i < $int ; $i++) {
if(!empty($port_answer[$i])){
$custom = array(
'pollsa_qid' => $new_id,
'pollsa_answers' => e($port_answer[$i]),
);
}
$insert_meta = $this->answers_model->insert($custom);
}
if($insert_meta === false){
Pf::database()->query('ROLLBACK');
}else{
Pf::database()->query('COMMIT');
}
}
Pf::database()->query('COMMIT');
}
$errors = Pf::validator()->get_readable_errors(false);
foreach ($errors as $key => $value) {
$error[$key][0] = $errors[$key][0];
}
$this->view->errors = $error; // error here!
$var['content'] = $this->view->fetch($template);
if (count($error) > 0){// and here!!!
$var['error'] = 1;
}else{
Pf::event()->trigger("action","polls-add-successfully",$this->polls_model->insert_id(),$data);
$var['error'] = 0;
$var['url'] = admin_url($this->action.'=index&ajax=&id=&token=');
}
echo json_encode($var);
}else{
$this->view->render($template);
}
}
I edited code, added function code.
This is my add function, if I want add poll with answers.
It gives me this error to my log.
I found this tutorial Undefined Variable error in View
I've googled it but didnt find anything special what helps me out.
Initiate the variable as an array.
because if the $error is empty the compiler will see it as an array.
if not it will get an error.
$error = [];
$errors = Pf::validator()->get_readable_errors(false);
foreach ($errors as $key => $value) {
// $error[$key][0] = $errors[$key][0];
// the right way is below
// i actually dont know what you want to do but this is the right way
// but providing [0] will make it some how constant.
$error[$key] = $errors[$key]
}
$this->view->errors = $error; // error showing here!
$var['content'] = $this->view->fetch($template);
if (count($error) > 0){ // and here???
$var['error'] = 1;
}else{
Pf::event()->trigger("action","polls-add-successfully",$this->polls_model->insert_id(),$data);
$var['error'] = 0;
$var['url'] = admin_url($this->action.'=index&ajax=&id=&token=');
}

Get database through email id in codeigniter

Controller[In Article Page Article Properly work with pagination, store user email id in 'articles' database , now i tried to get the user firstname, and lastname from users table but not work properly ]
public function articles()
{
$data['title'] = "Articles";
$config = array();
$config["base_url"] = base_url() . "sd/articles/";
$config["total_rows"] = $this->model_users->record_count_articles();
$config["per_page"] = 10;
$config["uri_segment"] = 3;
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$data["results"] = $this->model_users->fetch_result_articles($config["per_page"], $page);
$data["links"] = $this->pagination->create_links();
if ($this->session->userdata ('is_logged_in')){
$data['profile']=$this->model_users->profilefetch();
$this->load->view('sd/header',$data);
$this->load->view('sd/articles', $data);
$this->load->view('sd/footer', $data);
} else {
$this->load->view('sd/sdheader', $data);
$this->load->view('sd/articles', $data);
$this->load->view('sd/sdfooter', $data);
}
}
Model [ Get Users Name in Article Page ]
public function record_count_articles() {
return $this->db->where('status','1')->count_all("articles");
}
public function fetch_result_articles($limit, $start) {
$this->db->limit($limit, $start);
$query = $this->db->where('status','1')->order_by('id', 'DESC')->get("articles");
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
Add These Lines [ But Not Work]
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
$query = $this->db->select('firstname')->select('lastname')->where('email',$data[0]->email)->get("users");
$data['name_info']=$query->result_array();
}
return $data;
}
return false;
You have 2 problem here. please have a look on comments in code.
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
//1) $data[0]->email keep repeating same email.
// inner $query variable should be different.
$innerQuery = $this->db->select('firstname,lastname')->where('email',$row->email)->get("users");
//2) you need to store query result on array.
// $data['name_info'] stores only single record.
$data[]=$innerQuery ->result_array();
}
return $data;
}
return false;
You should avoid query in loop if you can achieve it by join
EDIT: Lets try this with join
public function fetch_result_articles($limit, $start) {
$this->db->limit($limit, $start);
$query = $this->db
->join('users u','u.email = a.email','left')
->where('a.status','1')->order_by('a.id', 'DESC')->get("articles a");
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
I have not tested the code. but it is better way than loop.

Categories