How to sort the data while searching according to the ratings they get and also for not those are not rated - laravel-5.7

I have a project of human resource management where I want to
display the ratings and non ratings jobseekers while searching as a
employer.
I have tried this but this only gives jobseekers whose ratings has been set.
public function search(Request $request)
{
$query = $request->get('query');
if (isset($query)) {
$queryParam = explode(' ', $query);
} else {
$queryParam = null;
}
$jobseekers = JobSeekers::where(function ($que) use ($queryParam) {
if (isset($queryParam)) {
foreach ($queryParam as $queries) {
$que->orWhere('job_seekers.category', 'like', '%' . $queries . '%');
$que->orWhere('job_seekers.keywords', 'like', '%' . $queries . '%');
$que->orWhere('job_seekers.experience', 'like', '%' . $queries . '%');
}
}
})->join('ratings', 'job_seekers.id', '=', 'ratings.js_id')
->groupBy('job_seekers.id')
->select('job_seekers.id', DB::raw('AVG( ratings.rating ) AS average_rating'))
->orderBy('average_rating', 'desc')
->get();
return view('search.search_all', compact('jobseekers'));
}
I have a rating table .
Schema::create('ratings', function (Blueprint $table) {
$table->increments('id');
$table->integer('emp_id')->unsigned();
$table->integer('js_id')->unsigned();
$table->integer('rating')->unsigned();
$table->longText('description')->nullable();
$table->foreign('emp_id')->references('id')->on('employers');
$table->foreign('js_id')->references('id')->on('job_seekers');
$table->timestamps();
});
I get data of only objects whose ratings is given but not for the
datas that exists but has no rating.

Try leftJoin() instead of join().
JOIN selects only results having data in joined table.
LEFT JOIN selects all results and attach data from the joined table.
public function search(Request $request)
{
$jobseekers = JobSeekers
::when($request->get('query'), function($query) use ($request) {
$words = explode(' ', $request->get('query'));
foreach($words as $word){
$query->orWhere('job_seekers.category', 'like', '%' . $word . '%');
$query->orWhere('job_seekers.keywords', 'like', '%' . $word . '%');
$query->orWhere('job_seekers.experience', 'like', '%' . $word . '%');
}
})
->leftJoin('ratings', 'job_seekers.id', '=', 'ratings.js_id')
->groupBy('job_seekers.id')
->select('job_seekers.id', DB::raw('AVG( ratings.rating ) AS average_rating'))
->orderBy('average_rating', 'desc')
->get();
return view('search.search_all', compact('jobseekers'));
}

Related

how to add nickname calumn in user list wordpress?

we we want to add 'nickname column' in user list WordPress...
and also the filter for the nickname ..
function new_modify_user_table1( $column ) {
$column['Nickname'] = 'Nickname';
return $column;
}
add_filter( 'manage_users_columns', 'new_modify_user_table1' );
function new_modify_user_table_row( $val, $column_name, $user_id ) {
switch ($column_name) {
case 'phone' :
return get_user_meta($user_id );
default:
case 'Nickname' :
return get_user_meta($user_id );
default:
}
return $val;
}
i have try to used the Search Results
get_user_meta() | Function but proper result i have not getting so please given the solution on it...
1.can you please give us solution on both how to get the nickname in column i.e "nickname"..
and also the want to filter for the nickname
You can use get_user_meta($user_id, $key, true) where $key can be one of the following:
user_pass, user_login, user_nicename, user_url, user_email, display_name, nickname, first_name, last_name, description, rich_editing, comment_shortcuts, admin_color, use_ssl, user_registered, show_admin_bar_front, role, locale
For example in your code you can use something like this:
function new_modify_user_table_row( $val, $column_name, $user_id ) {
switch ($column_name) {
case 'Email' :
return get_user_meta($user_id, 'user_email', true);
default:
case 'Nickname' :
return get_user_meta($user_id, 'nickname', true );
default:
}
return $val;
}

How to export image in excel file from mysql database dynamically

I want to export image from mysql database into an excel file using phpexcel.I have done it with static value but can not do it dynamically.
<?php
include ('config.php');
function my_constants(){
$url = 'http://' . $_SERVER['HTTP_HOST'] . "/phpexcel_gd/";
$path = $_SERVER['DOCUMENT_ROOT'] . '/phpexcel_gd/';
define('SITEURL', $url);
define('SITEPATH', str_replace('\\', '/', $path));
}
function report_details($display = null) {
if($display){
$imagePath = SITEURL . "images/";
} else {
$imagePath = SITEPATH . "images/";
}
// $select_query = mysqli_query($conn,"SELECT orderid, image_name,image_path FROM tbl_order_details WHERE orderid = '240419-0001-A1-B1'");
// $select_query_row = mysqli_fetch_array($select_query);
// $orderid = $select_query['orderid'];
// $image_name= $select_query['image_name'];
// $image_path = $select_query['image_path'];
$reportdetails = array(
// array('Image' => $image_path . $image_name,'orderid' => $orderid),
array('BrandIcon' => $imagePath . "github.png",'Comapany' => "Github",'Rank' => "3",'Link' => "https://github.com/"),
array('BrandIcon' => $imagePath . "bootstrap.png",'Comapany' => "Bootstrap",'Rank' => "4",'Link' => "http://getbootstrap.com/"),
array('BrandIcon' => $imagePath . "so-icon.png",'Comapany' => "Stack Overflow",'Rank' => "3",'Link' => "http://stackoverflow.com/"),
);
return $reportdetails;
}
/**
* Create excel by from ajax request
*/
function xlscreation_ajax() {
$reportdetails = report_details();
require_once SITEPATH . 'PHPExcel/Classes/PHPExcel.php';
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()
->setCreator("user")
->setLastModifiedBy("user")
->setTitle("Office 2007 XLSX Test Document")
->setSubject("Office 2007 XLSX Test Document")
->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
->setKeywords("office 2007 openxml php")
->setCategory("Test result file");
// Set the active Excel worksheet to sheet 0
$objPHPExcel->setActiveSheetIndex(0);
// Initialise the Excel row number
$rowCount = 0;
// Sheet cells
$cell_definition = array(
'A' => 'BrandIcon',
'B' => 'Company',
'C' => 'Rank',
'D' => 'Link'
);
// Build headers
foreach( $cell_definition as $column => $value )
{
$objPHPExcel->getActiveSheet()->getColumnDimension("{$column}")->setAutoSize(true);
$objPHPExcel->getActiveSheet()->setCellValue( "{$column}1", $value );
}
// Build cells
while( $rowCount < count($reportdetails) ){
$cell = $rowCount + 2;
foreach( $cell_definition as $column => $value ) {
$objPHPExcel->getActiveSheet()->getRowDimension($rowCount + 2)->setRowHeight(35);
switch ($value) {
case 'BrandIcon':
if (file_exists($reportdetails[$rowCount][$value])) {
$objDrawing = new PHPExcel_Worksheet_Drawing();
$objDrawing->setName('Customer Signature');
$objDrawing->setDescription('Customer Signature');
//Path to signature .jpg file
$signature = $reportdetails[$rowCount][$value];
$objDrawing->setPath($signature);
$objDrawing->setOffsetX(25); //setOffsetX works properly
$objDrawing->setOffsetY(10); //setOffsetY works properly
$objDrawing->setCoordinates($column.$cell); //set image to cell
$objDrawing->setWidth(32);
$objDrawing->setHeight(32); //signature height
$objDrawing->setWorksheet($objPHPExcel->getActiveSheet()); //save
} else {
$objPHPExcel->getActiveSheet()->setCellValue($column.$cell, "Image not found" );
}
break;
case 'Link':
//set the value of the cell
$objPHPExcel->getActiveSheet()->SetCellValue($column.$cell, $reportdetails[$rowCount][$value]);
//change the data type of the cell
$objPHPExcel->getActiveSheet()->getCell($column.$cell)->setDataType(PHPExcel_Cell_DataType::TYPE_STRING2);
///now set the link
$objPHPExcel->getActiveSheet()->getCell($column.$cell)->getHyperlink()->setUrl(strip_tags($reportdetails[$rowCount][$value]));
break;
default:
$objPHPExcel->getActiveSheet()->setCellValue($column.$cell, $reportdetails[$rowCount][$value] );
break;
}
}
$rowCount++;
}
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$saveExcelToLocalFile = saveExcelToLocalFile($objWriter);
$response = array(
'success' => true,
'filename' => $saveExcelToLocalFile['filename'],
'url' => $saveExcelToLocalFile['filePath']
);
echo json_encode($response);
die();
}
function saveExcelToLocalFile($objWriter) {
$rand = rand(1234, 9898);
$presentDate = date('YmdHis');
$fileName = "report_" . $rand . "_" . $presentDate . ".xlsx";
// make sure you have permission to write to directory
$filePath = SITEPATH . 'reports/' . $fileName;
$objWriter->save($filePath);
$data = array(
'filename' => $fileName,
'filePath' => $filePath
);
return $data;
}
?>
Here the $reportdetails contains the static array. How can I pass the mysql database value to the array dynamically? Please suggest any alternative other than phpexcel.

Extract URL from content

I have created a function where I need to extract URL from content. I don't know where did I go wrong. Here's my code..
function strip_url_content($content){
$strip = explode("\n", esc_html($content));
foreach($strip as $key => $single){
if (!filter_var($single, FILTER_VALIDATE_URL) === true) {
unset($strip[$key]);
}
}
return implode( ' ', $strip );
}

Symfony 1.4 deprecated function in php

Anyone know what is this error? I need help with this Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in C:\xampp\htdocs\sfprojects\jobeet\lib\vendor\symfony\lib\response\sfWebResponse.class.php on line 409. I'm using xampp 1.8.3 and symfony 1.4.
I couldn't get to step forward because of this a weeke a go :'(. Any help will be appreciated. Thank you.
In myproject/lib/vendor/symfony/lib/response/sfWebResponse.class.php on line 409
protected function normalizeHeaderName($name)
{
// return preg_replace('/\-(.)/e', "'-'.strtoupper('\\1')", strtr(ucfirst(strtolower($name)), '_', '-'));
return preg_replace_callback(
'/\-(.)/',
function ($matches) {
return '-'.strtoupper($matches[1]);
},
strtr(ucfirst(strtolower($name)), '_', '-')
);
}
FIX for pregtr method in /lib/vendor/symfony/lib/util/sfToolkit.class.php on line 360
public static function pregtr($search, $replacePairs){
// return preg_replace(array_keys($replacePairs), array_values($replacePairs), $search);
foreach($replacePairs as $pattern => $replacement)
{
if (preg_match('/(.*)e$/', $pattern, $matches))
{
$pattern = $matches[1];
$search = preg_replace_callback($pattern, function ($matches) use ($replacement) {
preg_match("/('::'\.)?([a-z]*)\('\\\\([0-9]{1})'\)/", $replacement, $match);
return ($match[1]==''?'':'::').call_user_func($match[2], $matches[$match[3]]);
}, $search);
}
else
{
$search = preg_replace($pattern, $replacement, $search);
}
}
return $search;
}
I've combined two answers from duplicate thread Symfony 1.4 using deprecated functions in php 5.5 answered by mika and xtech (up-vote them please)
It also affects /lib/form/addon/sfFormObject.class.php on line 281
protected function camelize($text)
{
//return preg_replace(array('#/(.?)#e', '/(^|_|-)+(.)/e'), array("'::'.strtoupper('\\1')", "strtoupper('\\2')"), $text); //ORIGINAL
return strtr(ucwords(strtr($text, array('/' => ':: ', '_' => ' ', '-' => ' '))), array(' ' => ''));
}
Found this:
http://blog.jakoubek.cz/symfony-1-4-deprecated-e-modifier
Tested, all changes look good
as this function is called in several files in sf 1.4, here are all changes that i made in my projects (based on different sources, including sf 1.4 forks):
lib/vendor/symfony/lib/command/sfCommandManager.class.php
## -108,7 +108,9 ## class sfCommandManager
else if (!is_array($arguments))
{
// hack to split arguments with spaces : --test="with some spaces"
- $arguments = preg_replace('/(\'|")(.+?)\\1/e', "str_replace(' ', '=PLACEHOLDER=', '\\2')", $arguments);
+ $arguments = preg_replace_callback('/(\'|")(.+?)\\1/', function ($match) {
+ return str_replace(' ', '=PLACEHOLDER=', $match[2]);
+ }, $arguments);
$arguments = preg_split('/\s+/', $arguments);
$arguments = str_replace('=PLACEHOLDER=', ' ', $arguments);
}
lib/vendor/symfony/lib/form/addon/sfFormObject.class.php
## -278,6 +278,6 ## abstract class sfFormObject extends BaseForm
protected function camelize($text)
{
- return preg_replace(array('#/(.?)#e', '/(^|_|-)+(.)/e'), array("'::'.strtoupper('\\1')", "strtoupper('\\2')"), $text);
+ return strtr(ucwords(strtr($text, array('/' => ':: ', '_' => ' ', '-' => ' '))), array(' ' => ''));
}
lib/vendor/symfony/lib/plugins/sfDoctrinePlugin/lib/form/sfFormFilterDoctrine.class.php
## -323,7 +323,7 ## abstract class sfFormFilterDoctrine extends sfFormFilter
protected function camelize($text)
{
- return sfToolkit::pregtr($text, array('#/(.?)#e' => "'::'.strtoupper('\\1')", '/(^|_|-)+(.)/e' => "strtoupper('\\2')"));
+ return strtr(ucwords(strtr($text, array('/' => ':: ', '_' => ' ', '-' => ' '))), array(' ' => ''));
}
lib/vendor/symfony/lib/plugins/sfPropelPlugin/lib/form/sfFormFilterPropel.class.php
## -263,6 +263,6 ## abstract class sfFormFilterPropel extends sfFormFilter
protected function camelize($text)
{
- return sfToolkit::pregtr($text, array('#/(.?)#e' => "'::'.strtoupper('\\1')", '/(^|_|-)+(.)/e' => "strtoupper('\\2')"));
+ return strtr(ucwords(strtr($text, array('/' => ':: ', '_' => ' ', '-' => ' '))), array(' ' => ''));
}
lib/vendor/symfony/lib/response/sfWebResponse.class.php
## -406,7 +406,7 ## class sfWebResponse extends sfResponse
protected function normalizeHeaderName($name)
{
- return preg_replace('/\-(.)/e', "'-'.strtoupper('\\1')", strtr(ucfirst(strtolower($name)), '_', '-'));
+ return strtr(ucwords(strtr(strtolower($name), array('_' => ' ', '-' => ' '))), array(' ' => '-'));
}
lib/vendor/symfony/lib/util/sfInflector.class.php
## -27,11 +27,7 ## class sfInflector
public static function camelize($lower_case_and_underscored_word)
{
- $tmp = $lower_case_and_underscored_word;
- $tmp = sfToolkit::pregtr($tmp, array('#/(.?)#e' => "'::'.strtoupper('\\1')",
- '/(^|_|-)+(.)/e' => "strtoupper('\\2')"));
-
- return $tmp;
+ return strtr(ucwords(strtr($lower_case_and_underscored_word, array('/' => ':: ', '_' => ' ', '-' => ' '))), array(' ' => ''));
}
beside, here is the fix for the E_NOTICE lib/vendor/symfony/lib/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Query/Abstract.php:
lib/vendor/symfony/lib/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Query/Abstract.php
## -1149,7 +1149,16 ## abstract class Doctrine_Query_Abstract
$copy->free();
if ($componentsBefore !== $componentsAfter) {
- return array_diff($componentsAfter, $componentsBefore);
+ $diff = array();
+
+ foreach($componentsAfter as $key => $val) {
+ if(!isset($componentsBefore[$key])) {
+ $diff[$key] = $val;
+ } elseif(is_array($componentsBefore[$key]) && !is_array($val)) {
+ $diff[$key] = $val;
+ }
+ }
+ return $diff;
} else {
return $componentsAfter;
}
You can unset the E_DEPRECATED flag in every application settings.yml :
dev:
.settings:
error_reporting: <?php echo ((E_ALL | E_STRICT) ^ E_DEPRECATED)."\n" ?>

Extending WP_List_Table / handling checkbox options in plugin administration

I'm working on a WordPress plugin, and part of that plugin requires extending WP_List_Table and storing any of the items which are checked in that table to an option. I've managed to figure out how to properly setup and display the required table, but how do I handle storing the checked options?
Here's what I've got so far...
class TDBar_List_Table extends WP_List_Table {
// Reference parent constructor
function __construct() {
global $status, $page;
// Set defaults
parent::__construct( array(
'singular' => 'theme',
'plural' => 'themes',
'ajax' => false
));
}
// Set table classes
function get_table_classes() {
return array('widefat', 'wp-list-table', 'themes');
}
// Setup default column
function column_default($item, $column_name) {
switch($column_name) {
case 'Title':
case 'URI':
case'Description':
return $item[$column_name];
default:
return print_r($item, true);
}
}
// Displaying checkboxes!
function column_cb($item) {
return sprintf(
'<input type="checkbox" name="%1$s" id="%2$s" value="checked" />',
//$this->_args['singular'],
$item['Stylesheet'] . '_status',
$item['Stylesheet'] . '_status'
);
}
// Display theme title
function column_title($item) {
return sprintf(
'<strong>%1$s</strong>',
$item['Title']
);
}
// Display theme preview
function column_preview($item) {
if (file_exists(get_theme_root() . '/' . $item['Stylesheet'] . '/screenshot.png')) {
$preview = get_theme_root_uri() . '/' . $item['Stylesheet'] . '/screenshot.png';
} else {
$preview = '';
}
return sprintf(
'<img src="%3$s" style="width: 150px;" />',
$preview,
$item['Title'],
$preview
);
}
// Display theme description
function column_description($item) {
if (isset($item['Version'])) {
$version = 'Version ' . $item['Version'];
if (isset($item['Author']) || isset($item['URI']))
$version .= ' | ';
} else {
$version = '';
}
if (isset($item['Author'])) {
$author = 'By ' . $item['Author'];
if (isset($item['URI']))
$author .= ' | ';
} else {
$author = '';
}
if (isset($item['URI'])) {
$uri = $item['URI'];
} else {
$uri = '';
}
return sprintf(
'<div class="theme-description"><p>%1$s</p></div><div class="second theme-version-author-uri">%2$s%3$s%4$s',
$item['Description'],
$version,
$author,
$uri
);
}
// Setup columns
function get_columns() {
$columns = array(
'cb' => '<input type="checkbox" />',
'title' => 'Theme',
'preview' => 'Preview',
'description' => 'Description'
);
return $columns;
}
// Make title column sortable
function get_sortable_columns() {
$sortable_columns = array(
'title' => array('Title', true)
);
return $sortable_columns;
}
// Setup bulk actions
function get_bulk_actions() {
$actions = array(
'update' => 'Update'
);
return $actions;
}
// Handle bulk actions
function process_bulk_action() {
// Define our data source
if (defined('WP_ALLOW_MULTISITE') && WP_ALLOW_MULTISITE == true) {
$themes = get_allowed_themes();
} else {
$themes = get_themes();
}
if ('update' === $this->current_action()) {
foreach ($themes as $theme) {
if ($theme['Stylesheet'] . '_status' == 'checked') {
// Do stuff - here's the problem
}
}
}
}
// Handle data preparation
function prepare_items() {
// How many records per page?
$per_page = 10;
// Define column headers
$columns = $this->get_columns();
$hidden = array();
$sortable = $this->get_sortable_columns();
// Build the array
$this->_column_headers = array($columns, $hidden, $sortable);
// Pass off bulk action
$this->process_bulk_action();
// Define our data source
if (defined('WP_ALLOW_MULTISITE') && WP_ALLOW_MULTISITE == true) {
$themes = get_allowed_themes();
} else {
$themes = get_themes();
}
// Handle sorting
function usort_reorder($a,$b) {
$orderby = (!empty($_REQUEST['orderby'])) ? $_REQUEST['orderby'] : 'Title';
$order = (!empty($_REQUEST['order'])) ? $_REQUEST['order'] : 'asc';
$result = strcmp($a[$orderby], $b[$orderby]);
return ($order === 'asc') ? $result : -$result;
}
usort($themes, 'usort_reorder');
//MAIN STUFF HERE
//for ($i = 0; i < count($themes); $i++) {
//}
// Figure out the current page and how many items there are
$current_page = $this->get_pagenum();
$total_items = count($themes);
// Only show the current page
$themes = array_slice($themes,(($current_page-1)*$per_page),$per_page);
// Display sorted data
$this->items = $themes;
// Register pagination options
$this->set_pagination_args( array(
'total_items' => $total_items,
'per_page' => $per_page,
'total_pages' => ceil($total_items/$per_page)
));
}
}
Problem is, I can't get it to save properly. I select the rows I want, hit save and it just resets.
I assume you are talking about the checkboxes in your table listing, so this will be how to process bulk actions.
All you need to do is add two new methods to your class and initialize it in the prepare_items method. I use the code below in one of my plugins to delete or export, but you can just as easily run an update.
/**
* Define our bulk actions
*
* #since 1.2
* #returns array() $actions Bulk actions
*/
function get_bulk_actions() {
$actions = array(
'delete' => __( 'Delete' , 'visual-form-builder'),
'export-all' => __( 'Export All' , 'visual-form-builder'),
'export-selected' => __( 'Export Selected' , 'visual-form-builder')
);
return $actions;
}
/**
* Process our bulk actions
*
* #since 1.2
*/
function process_bulk_action() {
$entry_id = ( is_array( $_REQUEST['entry'] ) ) ? $_REQUEST['entry'] : array( $_REQUEST['entry'] );
if ( 'delete' === $this->current_action() ) {
global $wpdb;
foreach ( $entry_id as $id ) {
$id = absint( $id );
$wpdb->query( "DELETE FROM $this->entries_table_name WHERE entries_id = $id" );
}
}
}
Now, call this method inside prepare_items() like so:
function prepare_items() {
//Do other stuff in here
/* Handle our bulk actions */
$this->process_bulk_action();
}
There's a fantastic helper plugin called Custom List Table Example that makes figuring out the WP_List_Table class much easier.

Resources