how can i get branch_id value but with different program_id condition?
$data = Peserta::where('branch_id',$branch_id)
->select('program_id')->distinct()
->with('program','branch');
return DataTables::of($data)
->addColumn('program', function ($data) {
return $data->program->name;
})
->addColumn('action', function ($data) {
$btn = ' check ';
return $btn;
})
->rawColumns(['program','action'])
->make(true);
Group the results using branch_id:
$data = Peserta::where('branch_id',$branch_id)
->select('program_id')->distinct()
->with('program','branch');
return DataTables::of($data)
->addColumn('program', function ($data) {
return $data->program->name;
})
->addColumn('action', function ($data) {
$btn = ' check ';
return $btn;
})
->rawColumns(['program','action'])
->groupBy('branch_id') // grouping the results
->make(true);
Related
I have this controller with many functions and cache keys depending on the username....
I need when updating the information and delete all cache keys for a specific user? is there any way to do that?
my controller to get data from caches:
class HomeController extends Controller
{
private $cache_duration = 60*60*72;
function home($uname) {
$info = Cache::remember('get-all-info-home'.$uname, $this->cache_duration, function() use($uname){
$user = User::where('name', '=', $uname)->firstOrFail();
return $user !=null ? $user->about : null;
});
return view('home', compact('info'));
}
function info($uname) {
$info = Cache::remember('get-all-info'.$uname, $this->cache_duration, function() use($uname){
$user = User::where('name', '=', $uname)->firstOrFail();
return $user !=null ? $user->about : null;
});
return view('info', compact(['info']));
}
function skills($uname) {
$info = Cache::remember('get-all-user-skills'.$uname, $this->cache_duration, function() use($uname){
$user = User::where('name', '=', $uname)->firstOrFail();
return $user !=null ? $user->about : null;
});
$skills = Cache::remember('get-all-skills'.$uname, $this->cache_duration, function() use($uname){
$user = User::where('name', '=', $uname)->firstOrFail();
return $user !=null ? $user->skills : null;
});
return view('skills', compact(['skills', 'info']));
}
I have tried this way, but still not working:
$uname = $info->user->name;
$keys = ['get-all-info-home', 'get-all-info', 'get-all-user-skills',
'get-all-skills', 'get-all-user-users-education-experiences', 'get-all-education',
'get-all-experiences', 'get-all-user-users-user-achievements', 'get-all-user-users-achievements',
'get-all-user-users-user-services', 'get-all-user-users-services-unique',
'get-all-user-users-user-services'];
foreach($keys as $key) {
$key = $key.$uname;
Cache::forget($key);
}
Similar to what lagbox mentioned, change to memcache or redis driver that supports tags, and add
Cache::
to
Cache::tags('user.....
in your controller method:
function home($uname) {
$info = Cache::tags('user'.$uname)
->remember('get-all-info-home'.$uname, $this->cache_duration, function() use($uname){
$user = User::where('name', '=', $uname)->firstOrFail();
return $user !=null ? $user->about : null;
});
return view('home', compact('info'));
}
function info($uname) {
$info = Cache::tags('user'.$uname)
->remember('get-all-info'.$uname, $this->cache_duration, function() use($uname){
$user = User::where('name', '=', $uname)->firstOrFail();
return $user !=null ? $user->about : null;
});
return view('info', compact(['info']));
}
then for the cache tag clear you would do:
Cache::tags('user'.$info->user->name)->flush()
if adding tagging is not not feasible for any reason, try checking and making sure that the $key.uname is actually returning the data you are expecting
foreach($keys as $key) {
$key = $key.$uname; // <- maybe this is not returning the right data
dd($key); // echo this out just to see if it is
Cache::forget($key);
}
We are using Laravel 8 for ecommerce. The built in search queries in Product categories, tags, product name, sku and brands. And its buffering so much for result to be appeared. And after appearing the result its being querying again automatically. And search result does not stay, if I put a space after search keyword then its going to appear the exact result.
After pressing backspace it starting a unlimited loop and the site stuck.
I have paste the full code for search here:
Ajax Search Function:
$('#search').on('keyup input change', function(){
search();
});
$('#search').on('focus', function(){
search();
});
function search(){
var searchKey = $('#search').val();
if(searchKey.length > 0){
$('body').addClass("typed-search-box-shown");
$('.typed-search-box').removeClass('d-none');
$('.search-preloader').removeClass('d-none');
$.post('{{ route('search.ajax') }}', { _token: AIZ.data.csrf, search:searchKey}, function(data){
if(data == '0'){
// $('.typed-search-box').addClass('d-none');
$('#search-content').html(null);
$('.typed-search-box .search-nothing').removeClass('d-none').html('Sorry, nothing found for <strong>"'+searchKey+'"</strong>');
$('.search-preloader').addClass('d-none');
}
else{
$('.typed-search-box .search-nothing').addClass('d-none').html(null);
$('#search-content').html(data);
$('.search-preloader').addClass('d-none');
}
});
}
else {
$('.typed-search-box').addClass('d-none');
$('body').removeClass("typed-search-box-shown");
}
}
Search Controller:
public function ajax_search(Request $request)
{
$keywords = array();
$products = Product::where('published', 1)->where('name', 'like', '%'.$request->search.'%')->get();
foreach ($products as $key => $product) {
foreach (explode(',',$product->name) as $key => $tag) {
if(stripos($tag, $request->search) !== false){
if(sizeof($keywords) > 4){
break;
}
else{
if(!in_array(strtolower($tag), $keywords)){
array_push($keywords, strtolower($tag));
}
}
}
}
}
$products = filter_products(Product::query());
$products = $products->where('published', 1)
->where(function ($q) use($request) {
$q->where('name', 'LIKE', '%'.$request->search.'%');
})
->get();
// $categories = Category::where('name', 'like', '%'.$request->search.'%')->get()->take(3);
// $shops = Shop::whereIn('user_id', verified_sellers_id())->where('name', 'like', '%'.$request->search.'%')->get()->take(3);
if(sizeof($keywords)>0 || sizeof($products)>0){
return view('frontend.partials.search_content', compact('products', 'keywords'));
}
return '0';
}
I have this database of user reports with this structure.
SQL DATABASE
I need to get the username out of the ids
the ids are in the tables "reportante" and "user_id_afectado"
These data are in the database
users.
Currently I only have the ids of the users I need to have the names as well but they are in another table.
I have this current code.
In ReportesDatatable.php
<?php
namespace App\Http\Controllers\Datatables;
use App\User;
use Carbon\Carbon;
use Yajra\DataTables\DataTables;
use App\Reportes;
class ReportesDatatable
{
public function ReportesDatatable()
{
$reportes = Reportes::get();
$usernameafectado = User::get();
//dd($usernameafectado[0]->name);
return Datatables::of($reportes)
->editColumn('user_id_afectado', function ($usernameafectado) {
return '<span data-popup="tooltip" data-placement="left" title="' . $usernameafectado[0]->name . '">' . $usernameafectado->name . '</span>';
})
->editColumn('created_at', function ($reportes) {
return '<span data-popup="tooltip" data-placement="left" title="' . $reportes->timestamp . '">' . $reportes->timestamp . '</span>';
})
->addColumn('action', function ($reportes) {
return '<div class="btn-group btn-group-justified"> Ver Reportante Afectado <i class="icon-circle-right2 text-white"></i></div>';
})
->rawColumns(['role', 'action', 'created_at'])
->make(true);
}
}
In my controller
//Solicitud reportes
public function verreportesadmin()
{
$usuarios = User::orderBy('id', 'DESC')->paginate(20);
//dd($usuarios);
$users = Reportes::orderBy('id', 'DESC')->paginate(20);
$count = $users->total();
return view('admin.verreportesadmin', array(
'users' => $users,
'usuarios' => $usuarios,
'count' => $count,
));
}
//Solicitud reportes
Currently I get this result where only the ids are shown.
Image RESULT
EDIT!!!! I FOUND SOLUTION I did it by doing a search with the id but I don't know if this is optimal for the server.
<?php
namespace App\Http\Controllers\Datatables;
use App\User;
use Carbon\Carbon;
use Yajra\DataTables\DataTables;
use App\Reportes;
class ReportesDatatable
{
public function ReportesDatatable()
{
$reportes = Reportes::get();
return Datatables::of($reportes)
->editColumn('reportante', function ($reportes) {
$reportante = User::find($reportes->reportante);
return $reportante->name;
})
->editColumn('user_id_afectado', function ($reportes) {
$nameafectado = User::find($reportes->user_id_afectado);
return $nameafectado->name;
})
->editColumn('created_at', function ($reportes) {
return '<span data-popup="tooltip" data-placement="left" title="' . $reportes->timestamp . '">' . $reportes->timestamp . '</span>';
})
->addColumn('action', function ($reportes) {
return '<div class="btn-group btn-group-justified"> Ver Reportante Afectado <i class="icon-circle-right2 text-white"></i></div>';
})
->rawColumns(['role', 'action', 'created_at'])
->make(true);
}
}
I FOUND SOLUTION I did it by doing a search with the id but I don't know if this is optimal for the server.
<?php
namespace App\Http\Controllers\Datatables;
use App\User;
use Carbon\Carbon;
use Yajra\DataTables\DataTables;
use App\Reportes;
class ReportesDatatable
{
public function ReportesDatatable()
{
$reportes = Reportes::get();
return Datatables::of($reportes)
->editColumn('reportante', function ($reportes) {
$reportante = User::find($reportes->reportante);
return $reportante->name;
})
->editColumn('user_id_afectado', function ($reportes) {
$nameafectado = User::find($reportes->user_id_afectado);
return $nameafectado->name;
})
->editColumn('created_at', function ($reportes) {
return '<span data-popup="tooltip" data-placement="left" title="' . $reportes->timestamp . '">' . $reportes->timestamp . '</span>';
})
->addColumn('action', function ($reportes) {
return '<div class="btn-group btn-group-justified"> Ver Reportante Afectado <i class="icon-circle-right2 text-white"></i></div>';
})
->rawColumns(['role', 'action', 'created_at'])
->make(true);
}
}
How can I cache custom query into redis. I am trying the following
public function __construct()
{
$this->orders_sql = Cache::remember('orders', 10, function () {
return $query = DB::connection('db1')->table('orders as o')
->leftJoin('addresses as pa', 'o.id', '=', 'pa.order_id')
->leftJoin('users as u', 'o.user_id', '=', 'u.id')
->leftJoin('clients', 'clients.user_id', '=', 'u.id')
->select(
'o.id as id', 'o.type as type', 'o.extra_info as extra_info', 'o.status as order_status', 'o.created_at as created_at', 'o.type as order_type', 'o.inspection_date as inspection_date', 'o.assignee as assignee', 'o.user_id as user_id', 'o.inspector_name as inspector_name',
'pa.address as address', 'pa.city as city', 'pa.state as state',
'clients.first_name as first_name', 'clients.middle_name as middle_name', 'clients.last_name as last_name'
)
->whereIn('o.status', OrderHelper::$ALLOWED_STATUS)
->where('o.type', '<>', OrderHelper::$CONSTRUCTION_EXISTING)
->where('o.deleted_at', null);
});
}
public function orders($sort_by, $sort_order, $limit, $filters)
{
if ($filters) {
$query = $this->applyFilters($filters);
}
$orders = $query->orderBy($sort_by ?? OrderHelper::$DEFAULT_SORT_COLUMN, $sort_order ?? OrderHelper::$DEFAULT_SORT_ORDER);
if ($limit === 'all') {
$orders = $orders->get();
} else {
$orders = $orders->get();
// $orders = $orders->paginate($limit ?? CommonHelper::$DEFAULT_PAGINATION_LIMIT);
}
//adding more information with orders such as Bank and address info
foreach ($orders as $order) {
$order->created_at = OrderHelper::getFormattedDate($order->id);
$order->draw = OrderHelper::draw($order->id);
$order->inspection_date = OrderHelper::getFormattedInspectionDate($order->inspection_date);
$order->client_name = $order->first_name . ' ' . $order->middle_name . ' ' . $order->last_name;
$order->type = OrderHelper::getFormattedOrderType($order);
if (empty($order->assignee)) {
$order->inspector_name = '-';
}
}
return $orders ? $orders : false;
}
And I am getting the error as
"message": "Serialization of 'Closure' is not allowed",
"exception": "Exception",
"file": "/var/www/api.local/vendor/laravel/framework/src/Illuminate/Cache/RedisStore.php",
"line": 295,
I'm guessing that you are using one of the laravel services like queue or something if yes in your case laravel tries uses serialize() function to serialize the class properties but one problem with serialize() function is that it cannot serialize closure that you are passing
anonymous functions cannot be serialized thats php behavior
What you can do is to try to assign the result to the property or pass the result to the constructor...
How to create api for search in lumen/laravel .. I tried using keyword but not working.
public function index(){
$Employees = Employees::all();
$page = Input::get('page', 1);
$keyword = Input::get('keyword', '');
if ($keyword!='') {
$keyword = Employees::
where("firstname", "LIKE","%$keyword%")
->orWhere("lastname", "LIKE", "%$keyword%");
}
$itemPerPage=5;
$count = Employees::count();
$offSet = ($page * $itemPerPage) - $itemPerPage;
$itemsForCurrentPage = array_slice($Employees->toArray(), $offSet, $itemPerPage);
return new LengthAwarePaginator($itemsForCurrentPage, count($Employees), $itemPerPage, $page,$keyword);
}
You should change this line :
if ($keyword!='') {
$Employees = Employees::
where("firstname", "LIKE","%$keyword%")
->orWhere("lastname", "LIKE", "%$keyword%")
->get();
}
Also i think You should the pagination within the model query, not on the returned result.
you can also do this
define your logic in a scope created in you model and consume it in your controller.here is what i mean
This should be in your model
public function scopeFilter($query, $params)
{
if ( isset($params['name']) && trim($params['name'] !== '') )
{
$query->where('name', 'LIKE', trim($params['name']) . '%');
}
if ( isset($params['state']) && trim($params['state'] !== '') )
{
$query->where('state', 'LIKE', trim($params['state']) . '%');
}
return $query;
}
and in your controller have something like
public function filter_property(Request $request)
{
$params = $request->except('_token');
$product = Product::filter($params)->get();
return response($product);
}
you can get more by reading scope on laravel doc and this blog post here