If clauses between where composition to laravel collect - laravel

Situation:
$post_1 = 'john';
$post_2 = 30;
$arr = array(['name'=>'john','number'=>70],['name'=>'clark','number'=>50]);
$collection = collect($arr);
if($post_1 == 'john')
{
$collection->where('name',$post_1);
}
if($post_2 == 70)
{
$collection->where('number',$post_2);
}
var_dump($collection->all());
But this doesn't work. I want to include filters but it depends on the post parameters to exist.

I think you can use when
$result= $collection->when(($post_1=="john"), function ($collection)use($post_1) {
return $collection->where('name',$post_1);
})->when(($post_2 == 70), function ($collection)use($post_2) {
return $collection->where('number',$post_2);
})->all();
dd($result);
or
$collection->when(($post_1=="john"), function ($collection)use($post_1) {
return $collection->where('name',$post_1);
})->when(($post_2 == 70), function ($collection)use($post_2) {
return $collection->where('number',$post_2);
});
dd($collection->all());
Ref:https://laravel.com/docs/8.x/collections#method-when

Related

Where function query withcount not working Laravel

this works perfectly fine
return Webinar::query()
->withCount('users')->orderByDesc('users_count')
->get();
but I need to use a condition for sorting, but this doesnt work
return Webinar::query()
->where(function($query) use ($sort_by) {
if($sort_by == 0) {
return $query->withCount('users')->orderByDesc('users_count');
} else {
return $query->withCount('review')->orderByDesc('review_count');
}
})
->get();
I also tried a condition inside like this to check my if else function
return Webinar::query()
->where(function($query) use ($sort_by) {
if($sort_by == 0) {
return $query->withCount('users')->orderByDesc('users_count')
->where('status', 2);
} else {
return $query->withCount('review')->orderByDesc('review_count')
->where('status', 1);
}
})
->get();
but the where status is only working not withcount. I hope someone can answer, thank you so much
How about you move condition code outside query
but I need to use a condition for sorting, but this doesnt work
if ($sort_by === 0) {
$order = 'users_count';
$count = 'users';
} else {
$order = 'review_count';
$count = 'review';
}
return Webinar::query()
->withCount('users')->orderByDesc($order)
->get();

How to get all routes within a route group?

I need to print a main menu and instead of having a database where the links/ routes are stored I thought it there would be a way to get all routes that are in a named group, but all I find is getting routes by action.
web.php
Route::group(['as' => 'main'], function () {
Route::get('/', function () {
return view('pages.start');
})->name('Home');
Route::get('/foobar', function () {
return view('pages.foobar');
})->name('Home');
Route::get('/business', function () {
return view('pages.business');
})->name('Business');
});
I was looking for something like:
$routes = getRoutesByGroup('main');
I cannot really believe that a function like that doesnt exist in current Laravel but I cant seem to find this. What am I missing?
Maybe this can solve partially in your case
function getRoutesByStarting($start = '')
{
$list = \Route::getRoutes()->getRoutesByName();
if (empty($start)) {
return $list;
}
$routes = [];
foreach ($list as $name => $route) {
if (\Illuminate\Support\Str::startsWith($name, $start)) {
$routes[$name] = $route;
}
}
return $routes;
}
usage
getRoutesByStarting('main')
More general solution
function getRoutesByGroup(array $group = [])
{
$list = \Route::getRoutes()->getRoutes();
if (empty($group)) {
return $list;
}
$routes = [];
foreach ($list as $route) {
$action = $route->getAction();
foreach ($group as $key => $value) {
if (empty($action[$key])) {
continue;
}
$actionValues = Arr::wrap($action[$key]);
$values = Arr::wrap($value);
foreach ($values as $single) {
foreach ($actionValues as $actionValue) {
if (Str::is($single, $actionValue)) {
$routes[] = $route;
} elseif($actionValue == $single) {
$routes[] = $route;
}
}
}
}
}
return $routes;
}
usage
getRoutesByGroup(['middleware' => 'api']);
getRoutesByGroup(['middleware' => ['api']]);
getRoutesByGroup(['as' => 'api']);
getRoutesByGroup(['as' => 'api*']);
getRoutesByGroup(['as' => ['api*', 'main']]);
$allRoutes = Route::getRoutes()->getRoutes(); // fetch all rotues as array
$name = 'main'; // specify your full route name
$grouped_routes = array_filter($allRoutes, function($route) use ($name) {
$action = $route->getAction(); // getting route action
if (isset($action['as'])) {
if (is_array($action['as'])) {
return in_array($name, $action['as']);
} else {
return $action['as'] == $name;
}
}
return false;
});
// output of route objects in the 'main' group
dd($grouped_routes);

Trying to get property 'model_name' of non-object

So I get this error when I'm trying to use the voyager themes, I want to use the voyager's theme since the page is on the admin side so I want to make it uniform.
I realized that I also need to to extend the views so I create this controller
<?php
namespace App\Http\Controllers\Admin;
use App\Models\Toko;
use App\Models\SubOrder;
use Illuminate\Http\Request;
use TCG\Voyager\Facades\Voyager;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use RealRashid\SweetAlert\Facades\Alert;
use Illuminate\Database\Eloquent\SoftDeletes;
use TCG\Voyager\Database\Schema\SchemaManager;
use TCG\Voyager\Http\Controllers\VoyagerBaseController;
class OrderController extends VoyagerBaseController
{
//***************************************
// ____
// | _ \
// | |_) |
// | _ <
// | |_) |
// |____/
//
// Browse our Data Type (B)READ
//
//****************************************
public function index(Request $request)
{
// GET THE SLUG, ex. 'posts', 'pages', etc.
$slug = $this->getSlug($request);
// GET THE DataType based on the slug
$dataType = Voyager::model('DataType')->where('slug', '=', $slug)->first();
// Check permission
$this->authorize('browse', app($dataType->model_name));
$getter = $dataType->server_side ? 'paginate' : 'get';
$search = (object) ['value' => $request->get('s'), 'key' => $request->get('key'), 'filter' => $request->get('filter')];
$searchNames = [];
if ($dataType->server_side) {
$searchable = SchemaManager::describeTable(app($dataType->model_name)->getTable())->pluck('name')->toArray();
$dataRow = Voyager::model('DataRow')->whereDataTypeId($dataType->id)->get();
foreach ($searchable as $key => $value) {
$field = $dataRow->where('field', $value)->first();
$displayName = ucwords(str_replace('_', ' ', $value));
if ($field !== null) {
$displayName = $field->getTranslatedAttribute('display_name');
}
$searchNames[$value] = $displayName;
}
}
$orderBy = $request->get('order_by', $dataType->order_column);
$sortOrder = $request->get('sort_order', $dataType->order_direction);
$usesSoftDeletes = false;
$showSoftDeleted = false;
// Next Get or Paginate the actual content from the MODEL that corresponds to the slug DataType
if (strlen($dataType->model_name) != 0) {
$model = app($dataType->model_name);
if ($dataType->scope && $dataType->scope != '' && method_exists($model, 'scope'.ucfirst($dataType->scope))) {
$query = $model->{$dataType->scope}();
} else {
$query = $model::select('*');
}
// Query menampilkan hanya toko pedagang
if(auth()->user()->hasRole('pedagang')) {
$query->where('user_id', auth()->id());
}
// Use withTrashed() if model uses SoftDeletes and if toggle is selected
if ($model && in_array(SoftDeletes::class, class_uses_recursive($model)) && Auth::user()->can('delete', app($dataType->model_name))) {
$usesSoftDeletes = true;
if ($request->get('showSoftDeleted')) {
$showSoftDeleted = true;
$query = $query->withTrashed();
}
}
// If a column has a relationship associated with it, we do not want to show that field
$this->removeRelationshipField($dataType, 'browse');
if ($search->value != '' && $search->key && $search->filter) {
$search_filter = ($search->filter == 'equals') ? '=' : 'LIKE';
$search_value = ($search->filter == 'equals') ? $search->value : '%'.$search->value.'%';
$query->where($search->key, $search_filter, $search_value);
}
if ($orderBy && in_array($orderBy, $dataType->fields())) {
$querySortOrder = (!empty($sortOrder)) ? $sortOrder : 'desc';
$dataTypeContent = call_user_func([
$query->orderBy($orderBy, $querySortOrder),
$getter,
]);
} elseif ($model->timestamps) {
$dataTypeContent = call_user_func([$query->latest($model::CREATED_AT), $getter]);
} else {
$dataTypeContent = call_user_func([$query->orderBy($model->getKeyName(), 'DESC'), $getter]);
}
// Replace relationships' keys for labels and create READ links if a slug is provided.
$dataTypeContent = $this->resolveRelations($dataTypeContent, $dataType);
} else {
// If Model doesn't exist, get data from table name
$dataTypeContent = call_user_func([DB::table($dataType->name), $getter]);
$model = false;
}
// Check if BREAD is Translatable
$isModelTranslatable = is_bread_translatable($model);
// Eagerload Relations
$this->eagerLoadRelations($dataTypeContent, $dataType, 'browse', $isModelTranslatable);
// Check if server side pagination is enabled
$isServerSide = isset($dataType->server_side) && $dataType->server_side;
// Check if a default search key is set
$defaultSearchKey = $dataType->default_search_key ?? null;
// Actions
$actions = [];
if (!empty($dataTypeContent->first())) {
foreach (Voyager::actions() as $action) {
$action = new $action($dataType, $dataTypeContent->first());
if ($action->shouldActionDisplayOnDataType()) {
$actions[] = $action;
}
}
}
// Define showCheckboxColumn
$showCheckboxColumn = false;
if (Auth::user()->can('delete', app($dataType->model_name))) {
$showCheckboxColumn = true;
} else {
foreach ($actions as $action) {
if (method_exists($action, 'massAction')) {
$showCheckboxColumn = true;
}
}
}
// Define orderColumn
$orderColumn = [];
if ($orderBy) {
$index = $dataType->browseRows->where('field', $orderBy)->keys()->first() + ($showCheckboxColumn ? 1 : 0);
$orderColumn = [[$index, $sortOrder ?? 'desc']];
}
$view = 'voyager::bread.browse';
if (view()->exists("voyager::$slug.browse")) {
$view = "voyager::$slug.browse";
}
// $order = SubOrder::class;
// $items = $order->items;
$tokoId = Toko::select('id')->firstWhere('user_id', auth()->id())->id;
// $orders = SubOrder::where('toko_id', $tokoId)->orderBy('created_at', 'desc')->get();
$orders = SubOrder::with('items')->where('toko_id', $tokoId)->orderBy('created_at', 'desc')->get();
return view('sellers.order.index', compact(
// 'items',
'orders',
'actions',
'dataType',
'dataTypeContent',
'isModelTranslatable',
'search',
'orderBy',
'orderColumn',
'sortOrder',
'searchNames',
'isServerSide',
'defaultSearchKey',
'usesSoftDeletes',
'showSoftDeleted',
'showCheckboxColumn'
));
}
// public function show(SubOrder $order)
// {
// $items = $order->items;
// return view('sellers.order.show', compact('items'));
// }
public function markTolak(SubOrder $suborder)
{
$suborder->status = 'gagal';
$suborder->save();
Alert::info('Order di Proses!', 'Order ditandai proses!');
return redirect('/seller/orders')->withMessage('Order ditandai proses');
}
public function markProses(SubOrder $suborder)
{
$suborder->status = 'proses';
$suborder->save();
Alert::info('Order di Proses!', 'Order ditandai proses!');
return redirect('/seller/orders')->withMessage('Order ditandai proses');
}
public function markDelivered(SubOrder $suborder)
{
$suborder->status = 'selesai';
$suborder->save();
// Check all sub order complete
$pendingSubOrders = $suborder->order->subOrders()->where('status','!=', 'selesai')->count();
if($pendingSubOrders == 0) {
$suborder->order()->update(['status'=>'selesai']);
}
Alert::success('Order Selesai!', 'Order ditandai selesai!');
return redirect('/seller/orders')->withMessage('Order ditandai selesai');
}
}
it shows that the error is from the line 42 where it checks the permission and couldn't find the "model_name". please help
Or maybe if there's another way to use the template?

Laravel: How to use multiple where with Request

This code is working. It checks for the exact barcode, case sensitive:
public function findpatronbarcode () {
if ($findpatronbarcode = \Request::get('q')) {
$patronbarcode = Patron::where(Patron::raw("BINARY `barcode`"), $findpatronbarcode)
->where('debarred', NULL)
->paginate(10);
}else{
$patronbarcode = ''; //If nothing found, don't return anything.
}
return $patronbarcode;
}
However, I need to add one more WHERE clause to check if Expiration is greater than today. I tried this but it does not work.
public function findpatronbarcode () {
if ($findpatronbarcode = \Request::get('q')) {
$patronbarcode = Patron::where(Patron::raw("BINARY `barcode`"), $findpatronbarcode)
->where('debarred', NULL)
->where('expiration','>',new Date())
->paginate(10);
}else{
$patronbarcode = ''; //If nothing found, don't return anything.
}
return $patronbarcode;
}
This should work:
public function findpatronbarcode () {
if ($findpatronbarcode = \Request::get('q')) {
$patronbarcode = Patron::where(Patron::raw("BINARY `barcode`"), $findpatronbarcode)
->where('debarred', NULL)
->whereDate('expiration','>', date('Y-m-d'))
->paginate(10);
}else{
$patronbarcode = ''; //If nothing found, don't return anything.
}
return $patronbarcode;
}
PS: as far as I understand, your question isn't about multiple "where" conditions in the request, as you've already achieved that in the working example, instead, it's about making a filter for date values.
Check Laravel 7.x Where Clauses docs(still true for version 5.x and 6.x)
public function findpatronbarcode () {
if ($findpatronbarcode = \Request::get('q')) {
$whereClauses= [[Patron::raw("BINARY `barcode`"), '=', $findpatronbarcode],
['debarred','=', NULL],
['expiration','>', Carbon::now()]];
$patronbarcode = Patron::where($whereClauses)->paginate(10);
}else{
$patronbarcode = ''; //If nothing found, don't return anything.
}
return $patronbarcode;
}

Laravel Eloquent Filtering Results

In my controller I retrieve a list of messages from the message model. I am trying to add a filter, but the filters are cancelling each other out.
// Controller
public function __construct(Message $messages)
{
$this->messages = $messages;
}
public function index($filter = null)
{
$messages = $this->messages
->actioned($filter == 'actioned' ? false : true)
->ignored($filter == 'ignored' ? true : false)
->get();
return view('...
}
// Model
public function scopeActioned($query, $actioned = true)
{
$constraint = ($actioned ? 'whereNotNull' : 'whereNull');
return $query->$constraint('ts_actioned');
}
public function scopeIgnored($query, $ignored = true)
{
return $query->where('is_ignored', ($ignored ? 'Yes' : 'No'));
}
How can I setup Eloquent so that scopeActioned is only called if $filter is set to 'actioned', and the same for ignored?
Simple Approach:
public function index($filter = null)
{
$query = $this->messages->query();
//applying filter
if($filter == 'actioned') {
$query->actioned();
}
if($filter == 'ignored') {
$query->ignored();
}
$messages = $query->get();
return view('...
}
Another Approach is work in Scope Function.
// Model
public function scopeActioned($query, $actioned = true)
{
if($actioned) {
$query->whereNotNull('ts_actioned');
}
return $query;
}
public function scopeIgnored($query, $ignored = true)
{
if($ignored) {
$query->where('is_ignored', 'Yes');
}
return $query;
}

Resources