How to get all routes within a route group? - laravel

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);

Related

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?

How to parse data on the backend

I am using Angular2 for my frontend and laravel for my back end and I'm having trouble saving the data to the database
Each of the keys in the Order[] (ex prodName, prodDesc) are the same as the column names in the database so I was trying to loop the request and save the data but its not working
public function Order(Request $request) {
$input = $request->all();
$order = new Order;
foreach ($input as $key => $value) {
if (array_key_exists($key, $input) && !empty($value)) {
$order->$key = $value;
}
}
}
if($order->save()) {
return response()->json(['order' => $order], 201);
}
order.interface.ts
export interface Order {
prodName: string;
prodDesc: string;
}
Adding the item to the order
addToOrder.component.ts
orders = [] as Order[];
saveItem(): void {
this.orders.push({prodName: this.prodName, prodDesc: this.prodDesc});
this.dataService.save(this.orders).then(() => {
this.navCtrl.pop(Search);
});
}
How each item is stored in storage
order.storage.ts
save(data : Order[]): Promise<any> {
return this.getData().then((products: any[]) => {
if (products) {
products = products.concat(data);
return this.storage.set('products', products);
}
return this.storage.set('products', data);
});
}
How I retrieve the order from storage
order.component.ts
private order = [] as Order[];
constructor(public dataService: OrderStorage, public OrderService: OrderService) {
this.dataService.getData().then((products) => {
if (products) {
this.order = products;
}
});
}
onSubmit() {
this.OrderService.submit(this.order)
.subscribe();
}
Posting the data to the back end
order.service.ts
submit(order: Order[]): Observable<any> {
return this.http.post(localapi.app, order)
.map(
(response: Response) => {});
}
Structure of the order data being sent
Retrieving the data on the backend
public function Order(Request $request) {
$input = $request->all();
var_dump($input);
}
the var_dump output
It's actually foreach ($input as $key => $arr), then you can use your loop:
foreach ($input as $arr) {
foreach ($arr as $key => $value) {
if (array_key_exists($key, $arr) && !empty($value)) {
$order->$key = $value;
}
}
}
The first set of elements you will encounter in your loop are arrays, then you can loop the property off of your array.

Return false limits multiple error message to one?

On my multiple upload library, I have a set error function.
On my upload function I use a in_array to check file extensions. If the in_array detects error it displays multiple error messages correct.
The problem I am having is for some reason when I use return FALSE; under the $this->set_error('file_extension_not_allowed') then will on display one message. Not sure why return FALSE limits error messages.
Question: How is it possible to use my return false but be able to display multiple message correct.
<?php
class Multiple_upload {
public $set_errors = array();
public function __construct($config = array()) {
$this->CI =& get_instance();
$this->files = $this->clean($_FILES);
empty($config) OR $this->set_config($config);
}
public function set_config($config) {
foreach ($config as $key => $value) {
$this->$key = $value;
}
return $this;
}
public function upload($field = 'userfile') {
$allowed_extension = explode('|', $this->allowed_types);
if (empty($this->upload_path)) {
$this->set_error('upload_path_not_set', 'upload_path_check');
return FALSE;
}
if (!realpath(FCPATH . $this->upload_path)) {
$this->set_error('upload_path_in_correct', 'location_check');
return FALSE;
}
if (!empty($this->files[$field]['name'][0])) {
foreach ($this->files[$field]['name'] as $key => $value) {
$this->file_name = $this->files[$field]['name'][$key];
$get_file_extension = explode('.', $this->files[$field]['name'][$key]);
$this->get_file_extension_end = strtolower(end($get_file_extension));
$array_1 = array(
$allowed_extension,
);
$array_2 = array(
$get_file_extension[1],
);
if (!in_array($array_2, $array_1)) {
$this->set_error('file_extension_not_allowed', 'extension_check');
return FALSE;
}
}
return $this;
}
}
public function set_error($message, $type) {
$this->CI->lang->load('upload', 'english');
$this->error_message[] = $this->CI->lang->line($message);
return $this;
}
public function display_error_messages($open_tag = '<p>', $close_tag = '</p>') {
foreach($this->error_message as $msg) {
var_dump($msg);
}
}
public function clean($data) {
if (is_array($data)) {
foreach ($data as $key => $value) {
unset($data[$key]);
$data[$this->clean($key)] = $this->clean($value);
}
} else {
$data = htmlspecialchars($data, ENT_COMPAT, 'UTF-8');
}
return $data;
}
}
Maybe this can help...
public function upload($field = 'userfile')
{
$allowed_extension = explode('|', $this->allowed_types);
if (empty($this->upload_path))
{
$this->set_error('upload_path_not_set', 'upload_path_check');
return FALSE;
}
if (!realpath(FCPATH . $this->upload_path))
{
$this->set_error('upload_path_in_correct', 'location_check');
return FALSE;
}
if (!empty($this->files[$field]['name'][0]))
{
$check_error = 0;//added this
foreach ($this->files[$field]['name'] as $key => $value)
{
$this->file_name = $this->files[$field]['name'][$key];
$get_file_extension = explode('.', $this->files[$field]['name'][$key]);
$this->get_file_extension_end = strtolower(end($get_file_extension));
$array_1 = array(
$allowed_extension,
);
$array_2 = array(
$get_file_extension[1],
);
if (!in_array($array_2, $array_1))
{
$this->set_error('file_extension_not_allowed', 'extension_check');
$check_error++;
}
}
if($check_error > 0 )
{
return FALSE;
}
return $this;
}
}

Laravel 5 controller returns controller

i have a controller function that needs to be redirected to a route with a different function to avoid redundancy of codes. is it possible to put a redirect to a different function?
Here is the code:
public function index()
{
$x = Auth::user()->id;
$id = DB::table('requests')->where('id', $x)->lists('userid');
if (!is_null($id)) {
$frnd = DB::table('users')->whereIn('id', $id)->get();
if (!is_null($frnd)) {
return view('friendlist', compact('frnd'));
} else {
$frnd = null;
return view('friendlist', compact('frnd'));
}
} else {
$frnd = null;
return view('friendlist', compact('frnd'));
}
}
public function respond()
{
$frnds = new Friend;
$id = Auth::user()->id;
$friendid = Request::input('friendid');
$frnds->id = $id;
$frnds->friendid = $friendid;
if (Input::get('accept')) {
$frnds->save();
}
DB::table('requests')->where('id', $id)->where('userid', $friendid)
return // this is where i should redirect to page with function index()
}
Name the index route in routes definition like this
Route::get('home', ['uses' => 'YourController#index', 'as' => 'home']);
Then use redirect method to redirect to this route:
return redirect()->route('home');
For more info on redirects use official docs
http://laravel.com/docs/5.1/responses#redirects
I don't think is a perfect, but someone prefer this way:
private function _index()
{
$x = Auth::user()->id;
$id = DB::table('requests')->where('id', $x)->lists('userid');
if (!is_null($id)) {
$frnd = DB::table('users')->whereIn('id', $id)->get();
if (!is_null($frnd)) {
return view('friendlist', compact('frnd'));
} else {
$frnd = null;
return view('friendlist', compact('frnd'));
}
} else {
$frnd = null;
return view('friendlist', compact('frnd'));
}
}
public function index()
{
$this->_index();
}
public function respond()
{
$frnds = new Friend;
$id = Auth::user()->id;
$friendid = Request::input('friendid');
$frnds->id = $id;
$frnds->friendid = $friendid;
if (Input::get('accept')) {
$frnds->save();
}
DB::table('requests')->where('id', $id)->where('userid', $friendid)
$this->_index();
}
private function for repeated code.

Unset sessions after form success not working

When I deselect my check box in my modify & access permissions it does not unset it from sessions if form is submitted success full.
What I am trying to achieve is on my edit function if any check box is not checked then it will unset from sessions when form is submitted success full. Because the reason need it unset from sessions is because when user logs in the permissions modify and access are set into sessions.
How can I make this work what I am after I have tried it in my edit but not unset when check box is empty
If i use this $this->session->unset_userdata('modify'); it unset all the modify array in sessions I just need it to unset the one that matches the unchecked check box.
public function edit() {
$this->load->model('admin/user/model_user_group');
if ($this->input->server('REQUEST_METHOD') == 'POST') {
$this->model_user_group->editUserGroup($this->uri->segment(4), $this->input->post());
if ($this->session->userdata('user_id') == TRUE) {
if (isset($_POST['permission[access]'])) {
$this->session->unset_userdata('permission[access]');
}
if (isset($_POST['permission[modify]'])) {
$this->session->unset_userdata('permission[modify]');
}
}
redirect('admin/users_group');
}
$this->getForm();
}
public function getForm() {
$data['title'] = "Users Group";
$this->load->model('admin/user/model_user_group');
$user_group_info = $this->model_user_group->getUserGroup($this->uri->segment(4));
if ($this->uri->segment(4) == FALSE) {
$data['name'] = $this->input->post('name');
} else {
$data['name'] = $user_group_info['name'];
}
if ($this->uri->segment(4) == FALSE) {
$data['user_group_id'] = $this->input->post('user_group_id');
} else {
$data['user_group_id'] = $user_group_info['user_group_id'];
}
$ignore = array(
'admin',
'dashboard',
'filemanager',
'login',
'menu',
'register',
'online',
'customer_total',
'user_total',
'chart',
'activity',
'logout',
'footer',
'header',
'permission'
);
$data['permissions'] = array();
$files = glob(FCPATH . 'application/modules/admin/controllers/*/*.php');
foreach ($files as $file) {
$permission = basename(strtolower($file), '.php');
if (!in_array($permission, $ignore)) {
$data['permissions'][] = $permission;
}
}
$permission_access = $this->input->post('permission');
if (isset($permission_access)) {
if (isset($permission_access['access'])) {
$data['access'] = $permission_access['access'];
} elseif (!empty($user_group_info['permission']['access'])) {
$data['access'] = $user_group_info['permission']['access'];
} else {
$data['access'] = array();
}
}
$permission_modify = $this->input->post('permission');
if (isset($permission_modify)) {
if (isset($permission_modify['modify'])) {
$data['modify'] = $permission_modify['modify'];
} elseif (!empty($user_group_info['permission']['modify'])) {
$data['modify'] = $user_group_info['permission']['modify'];
} else {
$data['modify'] = array();
}
}
$this->load->view('template/user/users_group_form.tpl', $data);
}
I have found away to get it working I have got sessions from database then re set the sessions in form, without using unset_sessions();
public function edit() {
$this->load->model('admin/user/model_user_group');
if ($this->input->server('REQUEST_METHOD') == 'POST') {
$this->model_user_group->editUserGroup($this->uri->segment(4), $this->input->post());
$user_group_query = $this->db->query("SELECT permission FROM " . $this->CI->db->dbprefix . "user_group
WHERE user_group_id = '" . (int)$this->session->userdata('user_group_id') . "'");
$permissions = unserialize($user_group_query->row('permission'));
$this->session->set_userdata($permissions);
redirect('admin/users_group');
}
$this->getForm();
}

Resources