Laravel 5.2 orWhere generate "and" in query - laravel

I have written a query in Laravel 5.2 as below, where I used scope. The scope scopeSubscriberCriteriaSearch have further sub scope. The scenario is, if the main scope finds "first_name" "=" "test" OR "last_name" "!=" "demo" etc, the related sub scope will be called.
$record = self::leftJoin("$customersTable as customers", 'customers.email', '=', "{$this->table}.email")
->leftJoin("$campaignsTable as campaigns", 'campaigns.campaign_id', '=', "{$this->table}.campaign_id")
->select("$this->primaryKey", "{$this->table}.first_name", "{$this->table}.last_name", "{$this->table}.email", "{$this->table}.phone", "{$this->table}.address", "campaigns.campaign_id", "campaigns.campaign_name", "customers.order_count")
->whereRaw($where);
$record->subscriberCriteriaSearch($criteria, $search_type, $persist)
->searchAfter($waiting_min, $search_type, $this->user_id)
->excludeLeadEmail($last_used_email)
->greaterCreateDateSearch($campaign_start_date)
->get();
===========
The main scope is as below:
public function scopeSubscriberCriteriaSearch($query, $criteria, $search_type, $persist = TRUE)
{
if (!empty($criteria))
{
$criteria_var = ['first_name', 'last_name', 'email', 'phone_number', 'city', 'country', 'state', 'zip', 'address', 'campaign', 'affiliate', 'subAffiliate', 'createdAt'];
return $query->where(function($sub_query) use ($criteria, $criteria_var, $search_type, $persist)
{
foreach ($criteria as $rule)
{
if (in_array($rule->condition, $criteria_var))
{
$position = array_search($rule->condition, $criteria_var);
($rule->condition == 'affiliate' || $rule->condition == 'subAffiliate') ? $sub_query->{$criteria_var[$position] . 'Search'}($rule->logical, $rule->input_val, $search_type, $persist) : $sub_query->{$criteria_var[$position] . 'Search'}($rule->logical, $rule->input_val, $persist);
}
}
});
}
}
The sub scopes (for example:) as below:
public function scopeFirst_nameSearch($query, $operator, $first_name, $persist = TRUE)
{
$query_operator = $this->getQueryOperator($operator);
if (!empty($operator) && !empty($first_name))
{
$query_operator_val = preg_match('/like/i', $query_operator) ? ($operator == 'starts' ? '"' . $first_name . '%"' : ($operator == 'ends' ? '"%' . $first_name . '"' : '"%' . $first_name . '%"')) : '"' . $first_name . '"';
return $persist ? $query->where($this->table . ".first_name", $query_operator, DB::raw($query_operator_val)) : $query->orWhere($this->table . ".first_name", $query_operator, DB::raw($query_operator_val));
}
}
public function scopeLast_nameSearch($query, $operator, $last_name, $persist = TRUE)
{
$query_operator = $this->getQueryOperator($operator);
if (!empty($operator) && !empty($last_name))
{
$query_operator_val = preg_match('/like/i', $query_operator) ? ($operator == 'starts' ? '"' . $last_name . '%"' : ($operator == 'ends' ? '"%' . $last_name . '"' : '"%' . $last_name . '%"')) : '"' . $last_name . '"';
return $persist ? $query->where($this->table . ".last_name", $query_operator, DB::raw($query_operator_val)) : $query->orWhere($this->table . ".last_name", $query_operator, DB::raw($query_operator_val));
}
}
So, if $persist is False, then the orWhere part of these sub queries will execute. But in my case, the query now generated as below:
select prospect_id, sem_1_prospects.first_name, sem_1_prospects.last_name, sem_1_prospects.email, sem_1_prospects.phone, sem_1_prospects.address, sem_campaigns.campaign_id, sem_campaigns.campaign_name, sem_customers.order_count from sem_1_prospects left join sem_1_customers as sem_customers on sem_customers.email = sem_1_prospects.email left join sem_1_campaigns as sem_campaigns on sem_campaigns.campaign_id = sem_1_prospects.campaign_id where ((sem_1_prospects.first_name = "test") and (sem_1_prospects.last_name NOT LIKE "%demo%"));
Can someone help me to find out the issue?

Related

Laravel advance search

I have created a multiform search in laravel & it's not working properly
I have a table name candidates & there is a row named salary in which it has value like shown the the below image from 1 lac(s) to 39 lac(s)
The meaning it's not working properly is if i search min salary = 0 & max salary = 4 it's showing data between 0 to 4 but it's also showing data like 10 18 22
controller code
public function advance(Request $request)
{
$data = \DB::table('candidates');
if( $request->name){
$data = $data->where('name', 'LIKE', "%" . $request->name . "%");
}
if( $request->location){
$data = $data->where('location', 'LIKE', "%" . $request->location . "%");
}
if( $request->key_skills){
$data = $data->where('key_skills', 'LIKE', "%" . $request->key_skills . "%");
}
if( $request->gender){
$data = $data->where('gender', 'LIKE', "%" . $request->gender . "%");
}
if( $request->pref_loc){
$data = $data->where('pref_loc', 'LIKE', "%" . $request->pref_loc . "%");
}
if( $request->phoneno){
$data = $data->where('phoneno', 'LIKE', "%" . $request->phoneno . "%");
}
if( $request->email){
$data = $data->where('email', 'LIKE', "%" . $request->email . "%");
}
$min_ctc = $request->min_ctc;
$max_ctc = $request->max_ctc;
if ($min_ctc || $max_ctc) {
$data = $data->where('salary', '>=', $min_ctc);
$data = $data->where('salary','<=',$max_ctc);
}
$data = $data->paginate(10);
$data2 = $data->total();
return view('search', compact('data2'))->with('data',$data);
}
Thanks in advance
You are trying to search on string not on integer. In order to get the required result you have to type cast the string to integer or float and then perform the operation.
Here is the script that might help you.
if ($min_ctc || $max_ctc) {
$data = $data->whereRaw("CONVERT(SUBSTRING_INDEX(salary,' ', 1),UNSIGNED INTEGER) >= {$min_ctc}");
$data = $data->whereRaw("CONVERT(SUBSTRING_INDEX(salary,' ', 1),UNSIGNED INTEGER) <= {$max_ctc}");
}

laravel-excel 3.1 with laravel framework 6.2 and php 7.4

I have problem with laravel-excel 3.1 after i have been upgrade laravel version and php version i got some requirement from laravel to upgrade laravel-excel too. after that i got problem with excel-export not support new version(3.1) before i use 2.1. anyone can help to update my currently code above? pls! and Thanks Guys!
private function export_customer_invoice_report($customer_invs)
{
$data_array = array([
'Issue Date',
'Purchase Order Invoice',
'Bag ID',
'SKU',
'Color-Size',
'QTY',
'Sale Price',
'Additional Discount',
'Actual Sale Price',
'Delivery Fee',
'Customer Balance',
'Pre-Paid Amount',
'Supplier Actual Price',
'Remark']);
foreach ($customer_invs as $key => $value) {
$product_variants = Helper::get_pro_option_id($value->order_item_id);
$doubleSpace = strip_tags($product_variants);
$singleSpace_product_variants = str_replace("\n ", "", $doubleSpace);
$issue_date = Helper::dateTimeDisplay($value->created_at);
$additional_dis = $value->additional_discount_percent ? $value->additional_discount_percent : 0;
$sale_price_after_disc = ($value->unit_price * $value->count_item) - ((($value->unit_price * $value->count_item) * $value->discount_percent) / 100);
$total_sale_price_discount_addit = ($sale_price_after_disc * $value->additional_discount_percent) / 100;
$actual_sale_price = $sale_price_after_disc - $total_sale_price_discount_addit;
// check if supplier actual price is zero, take from supplier price instead
$supplier_actual_price = $value->supplier_order_actual_price > 0
? $value->supplier_order_actual_price
: $value->supplier_price;
$data_list = array(
$issue_date,
$value->invoice_id,
$value->bag_id,
OrderItem::getProductSKU($value->order_item_id),
$singleSpace_product_variants,
$value->count_item,
'$' . number_format($sale_price_after_disc, 2),
'%' . $additional_dis,
'$' . number_format($actual_sale_price, 2),
'$' . number_format($value->delivery_price, 2),
'$' . number_format($value->customer_balance, 2),
'$' . number_format($value->prepaid_amount, 2),
'¥' . number_format($supplier_actual_price, 2),
$value->note,
);
array_push($data_array, $data_list);
}
Excel::create('customer_invoice_report', function ($excel) use ($data_array) {
// Set the title
$excel->setTitle('no title');
$excel->setCreator('no no creator')->setCompany('no company');
$excel->setDescription('report file');
$excel->sheet('sheet1', function ($sheet) use ($data_array) {
$sheet->cells('A1:M1', function ($cells) {
$cells->setBackground('#e7e7e7');
$cells->setFontWeight('bold');
});
$row = 1;
$startRow = -1;
$previousKey = '';
foreach ($data_array as $index => $value) {
if ($startRow == -1) {
$startRow = $row;
$previousKey = $value[2];
}
$sheet->setCellValue('A' . $row, $value[0]);
$sheet->setCellValue('B' . $row, $value[1]);
$sheet->setCellValue('C' . $row, $value[2]);
$sheet->setCellValue('D' . $row, $value[3]);
$sheet->setCellValue('E' . $row, $value[4]);
$sheet->setCellValue('F' . $row, $value[5]);
$sheet->setCellValue('G' . $row, $value[6]);
$sheet->setCellValue('H' . $row, $value[7]);
$sheet->setCellValue('I' . $row, $value[8]);
$sheet->setCellValue('J' . $row, $value[9]);
$sheet->setCellValue('K' . $row, $value[10]);
$sheet->setCellValue('L' . $row, $value[11]);
$sheet->setCellValue('M' . $row, $value[12]);
$sheet->setCellValue('N' . $row, $value[13]);
$nextKey = isset($data_array[$index + 1]) ? $data_array[$index + 1][2] : null;
if ($row >= $startRow && (($previousKey != $nextKey) || ($nextKey == null))) {
$cellToMergeJ = 'J' . $startRow . ':J' . $row;
$cellToMergeK = 'K' . $startRow . ':K' . $row;
$cellToMergeL = 'L' . $startRow . ':L' . $row;
$sheet->mergeCells($cellToMergeJ);
$sheet->mergeCells($cellToMergeK);
$sheet->mergeCells($cellToMergeL);
$sheet->cells('J' . $startRow . ':J' . $row, function ($cellsJ) {$cellsJ->setValignment('center');});
$sheet->cells('K' . $startRow . ':K' . $row, function ($cellsK) {$cellsK->setValignment('center');});
$sheet->cells('L' . $startRow . ':L' . $row, function ($cellsL) {$cellsL->setValignment('center');});
$startRow = -1;
}
$row++;
}
});
})->download('xlsx');
}
We just did this for a project. The laravel-excel package is very different when moving from 2.x to 3.x. The paradigm shifted from simply being a utility to representing imports and exports as self-contained classes. I would recommend moving all of your logic for generating the the export out of your controller and into this class, but you can keep it in your controller if you prefer. Here's the general idea of what you need to do:
First, create an export class:
php artisan make:export CustomerInvoiceReport
Then, edit the newly created class, which should be in app/Exports/CustomerInvoiceReport.php. If $customer_invs is an array, implement the FromArray interface. If it's a Laravel Collection, implement the FromCollection interface. Also, you can use the Exportable trait to add the download() method to the class (which we'll use later).
For this example, I'll assume it's an array. You need to modify the array() method so that it returns your modified array (I'll leave that to you):
namespace App\Exports;
use App\Invoice;
use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\Exportable;
class CustomerInvoiceExport implements FromArray
{
use Exportable;
protected $invoices;
public function __construct(array $invoices)
{
$this->invoices = $invoices;
}
public function array(): array
{
// insert/move your logic for modifying the array here
return $this->invoices;
}
}
Finally, in your controller, simply instantiate your export class and return a download:
use App\Exports\CustomerInvoiceReport;
...
private function export_customer_invoice_report($customer_invs)
{
return (new CustomerInvoiceReport($customer_invs))
->download('customer_invoice_report.xlsx');
}
There are other things you can control in the export class, such as column headers and formatting. Refer to the documentation on creating exports for more information.

Error the Trying to get property 'android_id' of non-object

I want to send notification to android devices using laravel.I do not want use package,and I am using curl to send query .I am write this codes but it has error but it gets the error Trying to get property 'android_id' of non-object .
I am create help.php
function send_notification_FCM($android_id, $title, $message, $id,$type) {
$accesstoken = env('FCM_KEY');
$URL = 'https://fcm.googleapis.com/fcm/send';
$post_data = '{
"to" : "' . $android_id . '",
"data" : {
"body" : "",
"title" : "' . $title . '",
"type" : "' . $type . '",
"id" : "' . $id . '",
"message" : "' . $message . '",
},
"notification" : {
"body" : "' . $message . '",
"title" : "' . $title . '",
"type" : "' . $type . '",
"id" : "' . $id . '",
"message" : "' . $message . '",
"icon" : "new",
"sound" : "default"
},
}';
// print_r($post_data);die;
$crl = curl_init();
$headr = array();
$headr[] = 'Content-type: application/json';
$headr[] = 'Authorization: ' . $accesstoken;
curl_setopt($crl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($crl, CURLOPT_URL, $URL);
curl_setopt($crl, CURLOPT_HTTPHEADER, $headr);
curl_setopt($crl, CURLOPT_POST, true);
curl_setopt($crl, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($crl, CURLOPT_RETURNTRANSFER, true);
$rest = curl_exec($crl);
if ($rest === false) {
// throw new Exception('Curl error: ' . curl_error($crl));
//print_r('Curl error: ' . curl_error($crl));
$result_noti = 0;
} else {
$result_noti = 1;
}
//curl_close($crl);
//print_r($result_noti);die;
return $result_noti;
}
and in the controller :
public function notifyUser(Request $request){
$user = User::where('id', $request->id)->first();
$android_id = $user->android_id;
$title = "Greeting Notification";
$message = "Have good day!";
$id = $user->id;
$type = "basic";
$res = send_notification_FCM($android_id, $title, $message, $id,$type);
if($res == 1){
echo 'success';
// success code
}else{
// fail code
}
}
and my rout :
Route::get('firebase/notification', 'firebaseNotificationController#notifyUser');
my database:
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('android_id')->nullable()->after('wallet');
});
}
$user = User::where('id', $request->id)->first();
the result of the first() method could be null, that because either of the wrong id or the request parameter is null, you should check it first:
$user = User::where('id', $request->id)->first();
if($user==null)
{
// fail finding user code
}
else
{
$android_id = $user->android_id;
$title = "Greeting Notification";
$message = "Have good day!";
$id = $user->id;
$type = "basic";
$res = send_notification_FCM($android_id, $title, $message, $id,$type);
if($res == 1){
echo 'success';
// success code
}else{
// fail code
}
}

How to pass a method on cases i dont need to use Laravel,Trying to get property 'id' of non-object

Hi there I have this problem on Laravel, I don't know how to explain it but I'll give my best, so forgive me if I am not to clear.
I have this on my controller for uploading images:
public function setUniqueNameAttribute(){
$this->unique_name = md5(Auth::user()->id . time());
}
public function getUniqueNameAttribute(){
return $this->unique_name;
}
public function uploadImage($request, $element, $id) {
if ($request->hasFile('question_image') || $request->hasFile('image_path') || $request->hasFile('avatar') || $request->hasFile('contact_image')) {
$thumbnailsRules = require_once __DIR__ . '/ThumbnailRules.php';
$this->setUniqueNameAttribute();
if($element == 'questions'){
$ImageToUpload = $request->file('question_image');
}elseif($element == 'answers'){
$ImageToUpload = $request->file('image_path');
}elseif($element == 'users'){
$ImageToUpload = $request->file('avatar');
}elseif($element == 'contacts'){
$ImageToUpload = $request->file('contact_image');
}
//create folders if they do not exist
foreach ($thumbnailsRules as $key => $rule) {
if (File::exists(storage_path('/app/public/institutions/' . $this->institution_storage . '/images/' . $element . '/' . $id . '/' . $rule['name'] . '/')) == false) {
Storage::disk('public')->makeDirectory('/institutions/' . $this->institution_storage . '/images/' . $element . '/' . $id . '/' . $rule['name']);
Storage::disk('public')->makeDirectory('/institutions/' . $this->institution_storage . '/images/' . $element . '/' . $id . '/original/');
}
}
//save the photos to the server
$image = Image::make($ImageToUpload);
$image->save(storage_path('/app/public/institutions/' . $this->institution_storage . '/images/' . $element . '/' . $id . '/original/' . $this->getUniqueNameAttribute() . '.jpeg'));
foreach ($thumbnailsRules as $key => $rule) {
$image = Image::make($ImageToUpload)->resize($rule['width'], $rule['height'], function ($c) {
$c->aspectRatio();
$c->upsize();
});
$image->save(storage_path('/app/public/institutions/' . $this->institution_storage . '/images/' . $element . '/' . $id . '/' . $rule['name'] . '/' . $this->getUniqueNameAttribute() . '.jpeg'));
}
}
}
This works fine for the question_image, image_path and avatar because this I use after I am logged in so I can use this:
$this->setUniqueNameAttribute();
But for contact image I have to use this before logged in so I don't need to use this:
$this->setUniqueNameAttribute();
This gives me this error:
Trying to get property 'id' of non-object
Is there a way to pass through this without getting an error..?

model and controller error CI

In my codeigniter controller user and user model currently I am trying to get the users from my database and have them as a table format on the view page.
I am getting two errors on my model though. I am trying to use sql. Database is auto loaded.
Not to sure what done wrong
Error 1
A PHP Error was encountered
Severity: Notice
Message: Undefined property: CI_DB_mysqli_result::$rows
Filename: user/user_model.php
Line Number: 46
Error 2
A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: user/user.php
Line Number: 75
My User Model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User_model extends CI_Model {
public function getTotalUsers() {
$query = $this->db->query("SELECT COUNT(*) AS total FROM `" . $this->db->dbprefix . "user`");
return $query->row('total');
}
public function getUsers($data = array()) {
$sql = "SELECT * FROM `" . $this->db->dbprefix . "user`";
$sort_data = array(
'username',
'status',
'date_added'
);
if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
$sql .= " ORDER BY " . $data['sort'];
} else {
$sql .= " ORDER BY username";
}
if (isset($data['order']) && ($data['order'] == 'DESC')) {
$sql .= " DESC";
} else {
$sql .= " ASC";
}
if (isset($data['start']) || isset($data['limit'])) {
if ($data['start'] < 0) {
$data['start'] = 0;
}
if ($data['limit'] < 1) {
$data['limit'] = 20;
}
$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
}
$query = $this->db->query($sql);
return $query->rows; // Line 46
}
}
User Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User extends MX_Controller {
public function __construct() {
parent::__construct();
$this->load->library('users');
$this->load->library('config_functions');
$this->load->model('user/user_model');
$this->load->model('user/User_group_model');
$this->lang->load('user/user', 'english');
$this->lang->load('english', 'english');
}
protected function getList() {
if (null !==($this->input->get('sort'))) {
$sort = $this->input->get('sort');
} else {
$sort = 'username';
}
if (null !==($this->input->get('order'))) {
$order = $this->input->get('order');
} else {
$order = 'ASC';
}
if (null !==($this->input->get('page'))) {
$page = $this->input->get('page');
} else {
$page = 1;
}
$url = '';
if (null !==($this->input->get('sort'))) {
$url .= '&sort=' . $this->input->get('sort');
}
if (null !==($this->input->get('order'))) {
$url .= '&order=' . $this->input->get('order');
}
if (null !==($this->input->get('page'))) {
$url .= '&page=' . $this->input->get('page');
}
$data['users'] = array();
$filter_data = array(
'sort' => $sort,
'order' => $order,
'start' => ($page - 1) * $this->config_functions->get('config_limit_admin'),
'limit' => $this->config_functions->get('config_limit_admin')
);
$user_total = $this->user_model->getTotalUsers();
$results = $this->user_model->getUsers($filter_data);
foreach ($results as $result) { // Line 75
$data['users'][] = array(
'user_id' => $result['user_id'],
'username' => $result['username'],
'status' => ($result['status'] ? $this->lang->line('text_enabled') : $this->lang->line('text_disabled')),
'date_added' => date($this->lang->line('date_format_short'), strtotime($result['date_added']))
);
}
$this->load->view('template/user/user_list', $data);
}
}
You may try this:
Change
return $query->rows; // Line 46
To
return $query->result_array();
$query->result() gives object notation, and $query->result_array() gives a array notation.
If you have used $query->result(), your foreach would be like:
foreach ($results as $result) { // Line 75
$data['users'][] = array(
'user_id' => $result->user_id, //the object type
...
);
}
"$query->rows()" does not exist in codeigniter active record class.
you will need to use $query->result() or $query->result_array() instead

Resources