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?
Related
i have Product Model and it have bread in voyager and everything is ok.
Products have publisher_id column if null == main else int(id of publisher).
i want create multiple browse blade but one of those is default voyager blade
and another where('publisher_id','!=',null)
to show .
how to created it with route ?
thanks .
fixed with resource route
Route::resource('products/index/publisher', VoyagerProductPublisherController::class);
Route::resource('products/index/notaccept', VoyagerProductPublisherNotAcceptController::class);
and then in controllers index function write query
public function index(Request $request)
{
// GET THE SLUG, ex. 'posts', 'pages', etc.
$slug = \request()->segment(3);
// GET THE DataType based on the slug
$dataType = Voyager::model('DataType')->where('slug', '=', $slug)->first();
// Check permission
$getter = 'paginate';
$search = (object)['value' => $request->get('s'), 'key' => $request->get('key'), 'filter' => $request->get('filter')];
$searchNames = [];
if ($dataType->server_side) {
$searchNames = $dataType->browseRows->mapWithKeys(function ($row) {
return [$row['field'] => $row->getTranslatedAttribute('display_name')];
});
}
$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);
$query = $model::select($dataType->name . '.*');
if ($dataType->scope && $dataType->scope != '' && method_exists($model, 'scope' . ucfirst($dataType->scope))) {
$query->{$dataType->scope}();
}
// Use withTrashed() if model uses SoftDeletes and if toggle is selected
if ($model && in_array(SoftDeletes::class, class_uses_recursive($model))) {
$usesSoftDeletes = true;
if ($request->showSoftDeleted && $request->showSoftDeleted == 1) {
$showSoftDeleted = true;
$query = $query->onlyTrashed();
}
}
// 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 . '%';
$searchField = $dataType->name . '.' . $search->key;
if ($row = $this->findSearchableRelationshipRow($dataType->rows->where('type', 'relationship'), $search->key)) {
$query->whereIn(
$searchField,
$row->details->model::where($row->details->label, $search_filter, $search_value)->pluck('id')->toArray()
);
} else {
if ($dataType->browseRows->pluck('field')->contains($search->key)) {
$query->where($searchField, $search_filter, $search_value);
}
}
}
$row = $dataType->rows->where('field', $orderBy)->firstWhere('type', 'relationship');
if ($orderBy && (in_array($orderBy, $dataType->fields()) || !empty($row))) {
$querySortOrder = (!empty($sortOrder)) ? $sortOrder : 'desc';
if (!empty($row)) {
$query->select([
$dataType->name . '.*',
'joined.' . $row->details->label . ' as ' . $orderBy,
])->leftJoin(
$row->details->table . ' as joined',
$dataType->name . '.' . $row->details->column,
'joined.' . $row->details->key,
);
}
$dataTypeContent = call_user_func([
$query->orderBy($orderBy, $querySortOrder)->where('publisher_id','!=',null),
$getter,
]);
} elseif ($model->timestamps) {
$dataTypeContent = call_user_func([$query->latest($model::CREATED_AT)->where('publisher_id','!=',null), 'paginate'], request()->perPage ?? 10);
} else {
$dataTypeContent = call_user_func([$query->orderBy($model->getKeyName(), 'DESC')->where('publisher_id','!=',null), $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)->where('publisher_id','!=',null), $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::guard('admin')->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']];
}
// Define list of columns that can be sorted server side
$sortableColumns = $this->getSortableColumns($dataType->browseRows);
$view = 'voyager::bread.publisher';
if (view()->exists("voyager::$slug.publisher")) {
$view = "voyager::$slug.publisher";
}
return Voyager::view($view, compact(
'actions',
'dataType',
'dataTypeContent',
'isModelTranslatable',
'search',
'orderBy',
'orderColumn',
'sortableColumns',
'sortOrder',
'searchNames',
'isServerSide',
'defaultSearchKey',
'usesSoftDeletes',
'showSoftDeleted',
'showCheckboxColumn'
));
}
// in controller two
public function index(Request $request)
{
// GET THE SLUG, ex. 'posts', 'pages', etc.
$slug = \request()->segment(3);
// GET THE DataType based on the slug
$dataType = Voyager::model('DataType')->where('slug', '=', $slug)->first();
// Check permission
$getter = 'paginate';
$search = (object)['value' => $request->get('s'), 'key' => $request->get('key'), 'filter' => $request->get('filter')];
$searchNames = [];
if ($dataType->server_side) {
$searchNames = $dataType->browseRows->mapWithKeys(function ($row) {
return [$row['field'] => $row->getTranslatedAttribute('display_name')];
});
}
$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);
$query = $model::select($dataType->name . '.*');
if ($dataType->scope && $dataType->scope != '' && method_exists($model, 'scope' . ucfirst($dataType->scope))) {
$query->{$dataType->scope}();
}
// Use withTrashed() if model uses SoftDeletes and if toggle is selected
if ($model && in_array(SoftDeletes::class, class_uses_recursive($model))) {
$usesSoftDeletes = true;
if ($request->showSoftDeleted && $request->showSoftDeleted == 1) {
$showSoftDeleted = true;
$query = $query->onlyTrashed();
}
}
// 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 . '%';
$searchField = $dataType->name . '.' . $search->key;
if ($row = $this->findSearchableRelationshipRow($dataType->rows->where('type', 'relationship'), $search->key)) {
$query->whereIn(
$searchField,
$row->details->model::where($row->details->label, $search_filter, $search_value)->pluck('id')->toArray()
);
} else {
if ($dataType->browseRows->pluck('field')->contains($search->key)) {
$query->where($searchField, $search_filter, $search_value);
}
}
}
$row = $dataType->rows->where('field', $orderBy)->firstWhere('type', 'relationship');
if ($orderBy && (in_array($orderBy, $dataType->fields()) || !empty($row))) {
$querySortOrder = (!empty($sortOrder)) ? $sortOrder : 'desc';
if (!empty($row)) {
$query->select([
$dataType->name . '.*',
'joined.' . $row->details->label . ' as ' . $orderBy,
])->leftJoin(
$row->details->table . ' as joined',
$dataType->name . '.' . $row->details->column,
'joined.' . $row->details->key,
);
}
$dataTypeContent = call_user_func([
$query->orderBy($orderBy, $querySortOrder)->where('accept',0),
$getter,
]);
} elseif ($model->timestamps) {
$dataTypeContent = call_user_func([$query->latest($model::CREATED_AT)->where('accept',0), 'paginate'], request()->perPage ?? 10);
} else {
$dataTypeContent = call_user_func([$query->orderBy($model->getKeyName(), 'DESC')->where('accept',0), $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)->where('accept',0), $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::guard('admin')->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']];
}
// Define list of columns that can be sorted server side
$sortableColumns = $this->getSortableColumns($dataType->browseRows);
$view = 'voyager::bread.notaccept';
if (view()->exists("voyager::$slug.notaccept")) {
$view = "voyager::$slug.notaccept";
}
return Voyager::view($view, compact(
'actions',
'dataType',
'dataTypeContent',
'isModelTranslatable',
'search',
'orderBy',
'orderColumn',
'sortableColumns',
'sortOrder',
'searchNames',
'isServerSide',
'defaultSearchKey',
'usesSoftDeletes',
'showSoftDeleted',
'showCheckboxColumn'
));
}
thanks for view .
I have noticed that some of my files in PhpStorm does not detect any changes while in other files I can see the changes immediately if I did some code changes.
Is there a way to find where in the PhpStorm settings to auto-detect all files edited?
I've already checked my .gitignore file but I can't see the untrackable file isn't there.
For instance, in my UserScopeTrait.php file, I did code changes and I've seen changes automatically when I git status. but in my UserTrait.php file if I made changes in it there are no changes found.
Here are the exact files I've made some changes:
This is the UserScopeTrait.php file and this can be auto detected file changes:
<?PHP
namespace App\Traits;
use App\Jobs\SendEmployeeInvitationEmail;
use App\Jobs\SendEmployeeInvitationMondayTuesdayJob;
use App\Jobs\UpdateAdminEmployeeSurvey;
use App\Language;
use App\Location;
use App\LocationManager;
use App\Mail\SendWeeklySurvey;
use App\Mail\SurveyResultsAvailableNotification;
use App\Mail\SurveySentNotification;
use App\Repositories\UserCompanyRepository;
use App\Survey;
use App\Team;
use App\TeamManager;
use App\User;
use App\UserCompany;
use App\UsersAnswer;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Mail;
trait UserScopeTrait
{
public function scopeDispatchEmployeeInvites($query)
{
$users = $query->whereHas('userCompany', function ($company) {
$company->where('company_id', auth()->user()->company->id)->where('role_name', 'employee');
})->where('invite_sent', 0)->get();
$auth = auth()->user();
$dispatcher = new User();
$toSend = 0;
$notifyState = [];
// this is the changes I've made
adsfdsfasdfas
if ($users->count() == 5) {
/**
* first survey batch send
* date of action: all days except Monday, Tuesday
* send invitation & update survey details for admin and then mimic admin survey details to employee
*/
if (!Carbon::now()->isMonday() && !Carbon::now()->isTuesday()) {
$this->updateSurveyDetailsAdminEmployee(null, $auth, 'admin');
}
}
foreach ($users as $employee) {
$notifyState['total'] = $users->count();
$employee->invite_sent = true;
$employee->save();
$toSend++;
if ($notifyState['total'] == $toSend) {
$notifyState['last'] = true;
// Admin receive an email notification about surveys sent
$dispatcher->dispatchAdminSurveySentNotification($auth);
} else {
$notifyState['last'] = false;
}
/**
* counter reaches to 5 this means that this is the first survey
* and should update survey details for both admin & employee
*/
if ($users->count() == 5) {
if (Carbon::now()->isMonday()||Carbon::now()->isTuesday()) {
/**
* first survey batch send
* date of action: Monday, Tuesday
* send invitation only
*/
SendEmployeeInvitationMondayTuesdayJob::dispatch($employee, auth()->user())->onQueue('notification');
} else {
/**
* first survey batch send
* date of action: all days except Monday, Tuesday
* send invitation & mimic admin survey details to employee
*/
$this->updateSurveyDetailsAdminEmployee($employee, $auth, 'employee');
SendEmployeeInvitationEmail::dispatch($auth, $employee, $notifyState)->onQueue('notification');
}
}
/**
* not first survey batch & single execution
*/
else {
if ($users->count() >=2 && $users->count() <= 3) {
/**
* not first survey batch execution
* date of action: Monday, Tuesday
* send invitation only
*/
if (Carbon::now()->isMonday()||Carbon::now()->isTuesday()) {
SendEmployeeInvitationMondayTuesdayJob::dispatch($employee, auth()->user())->onQueue('notification');
}
/**
* not first survey batch execution
* date of action: all days except Monday, Tuesday
* send invitation & update survey details for employee only mimic admin survey details
*/
else {
$this->updateSurveyDetailsAdminEmployee($employee, $auth, 'employee');
SendEmployeeInvitationEmail::dispatch($auth, $employee, $notifyState)->onQueue('notification');
}
}
if ($users->count() == 1) {
/**
* not first survey single execution
* date of action: Monday, Tuesday
* send invitation only
*/
if (Carbon::now()->isMonday()||Carbon::now()->isTuesday()) {
SendEmployeeInvitationMondayTuesdayJob::dispatch($employee, auth()->user())->onQueue('notification');
}
/**
* not first survey single execution
* date of action: all days except Monday, Tuesday
* send invitation & update survey details for employee mimic admin survey details
*/
else {
$this->updateSurveyDetailsAdminEmployee($employee, $auth, 'employee');
SendEmployeeInvitationEmail::dispatch($auth, $employee, $notifyState)->onQueue('notification');
}
}
}
}
}
private function updateSurveyDetailsAdminEmployee($employee, $auth, $type)
{
$currentDate = Carbon::now();
$nextSurveyDate = clone $currentDate;
if ($type == 'admin') {
date_default_timezone_set($auth->timezone);
// Set next_survey_date base on account owner survey frequency setting
if ($auth->account->survey_frequency == 'every_week_wednesday') {
$nextSurveyDate = $nextSurveyDate->next(Carbon::WEDNESDAY);
} else {
$nextSurveyDate = $nextSurveyDate->next(Carbon::WEDNESDAY)->next(Carbon::WEDNESDAY);
}
// Update survey_date and next_survey_number for admin
$auth->current_survey_date = $currentDate;
$auth->next_survey_date = $nextSurveyDate;
$auth->first_survey = true;
$auth->next_survey_number = (new User())->getNextSurveyNumber($auth);
$auth->save();
}
else if ($type == 'employee') {
date_default_timezone_set($employee->timezone);
// Update next_survey_date and next_survey_number for employee
$employee->next_survey_date = $auth->next_survey_date;
$employee->current_survey_id = $auth->current_survey_id;
$employee->current_survey_date = $currentDate;
$employee->next_survey_number = $auth->next_survey_number;
$employee->invite_sent_time = now()->toDateTimeString();
$employee->save();
}
}
public function scopeUpdateMessageNotificationCounter($query, $data)
{
$managers = $query->whereHas('userCompany', function ($userCompany) use ($data) {
$userCompany->where('company_id', (new User())->authUserCompanyId())->where('role_name', 'manager');
})->get();
foreach ($managers as $user) {
$user->wait_for_my_reply = $data['waitingForMyReply'];
$user->wait_for_employee_organization_reply = $data['waitingForEmployeeOrganizationReply'];
$user->save();
}
$admin = User::whereHas('company', function ($company) {
$company->where('id', (new User())->authUserCompanyId());
})->first();
$admin->wait_for_my_reply = $data['waitingForMyReply'];
$admin->wait_for_employee_organization_reply = $data['waitingForEmployeeOrganizationReply'];
$admin->save();
}
public function scopeUserHasSurvey($query, $id)
{
$currentSurveyDate = $query->find($id)->current_survey_date;
$nextSurveyDate = $query->find($id)->next_survey_date;
if ($currentSurveyDate != null && $nextSurveyDate != null) {
return true;
} else {
return false;
}
}
public function scopeUserCompanyId($query, $id)
{
return $query->find($id)->company->id;
}
public function scopeUserCurrentSurveyId($query, $id)
{
return $query->find($id)->current_survey_id;
}
public function scopeFilterAdminAccess()
{
if (auth()->user()->freeze_account > 0 && auth()->user()->role_name == 'admin') {
return redirect()->route('billing')->with(['info' => 'Your account is freeze']);
}
}
public function scopeActiveAdmin($query)
{
$query = $query->role('admin')->where('freeze_account', 0);
$query = $query->whereNotNull('email_verified_at')->where('active', 1)->get();
return $query;
}
public function scopeTrialGracePeriodActiveAdmin($query)
{
return $query->role('admin')
->where('freeze_account', 0)
->whereNotNull('email_verified_at')
->where('active', 1)
->where('trial_grace_period', true);
}
public function scopeActiveEmployee($query, $companyId)
{
$query = $query->whereHas('roles', function ($roles) {
$roles->where('name', 'employee');
});
$query = $query->whereNotNull('email_verified_at')->where('active', 1);
$query = $query->whereHas('userCompany', function ($userCompany) use ($companyId) {
$userCompany->where('company_id', $companyId);
})->get();
return $query->count();
}
public function scopeAdminReplies($query)
{
$query = $query->whereHas('company', function ($company) {
$company->where('id', (new User())->authUserCompanyId());
})->first();
return $query->total_replies;
}
public function scopeIncrementReplies($query, $message)
{
$query = $query->whereHas('company', function ($company) {
$company->where('id', (new User())->authUserCompanyId());
})->first();
if (!is_null($message)) {
$query->increment('total_replies');
}
}
public function scopeSendSurveyResultNotification($query)
{
$user = new User();
$admin = $query->whereHas('company', function ($company) {
$company->where('id', (new User())->authUserCompanyId());
})->first();
// process survey result for admin
$user->processSurveyResult($admin);
$managers = User::whereHas('userCompany', function ($userCompany) use ($admin) {
$userCompany->where('company_id', $admin->company->id)->where('role_name', 'manager');
})->get();
if ($managers->count() > 0) {
foreach ($managers as $manager) {
// process survey result for manager
$user->processSurveyResultManager($manager);
}
}
}
public function scopeIncrementUserColumn($query, $column)
{
$query = $query->whereHas('company', function ($company) {
$company->where('id', (new User())->authUserCompanyId());
})->first();
switch ($column) {
case 'surveys_completed':
$query->increment('surveys_completed');
break;
case 'email_notification_sent':
$query->increment('email_notification_sent');
break;
case 'cheers_sent':
$query->increment('cheers_sent');
break;
case 'resolved_issues':
$query->increment('resolved_issues');
break;
case 'total_answers':
$query->increment('total_answers');
break;
case 'uncompleted_replies':
$query->increment('uncompleted_replies');
break;
case 'add_more':
$query->increment('add_more');
break;
}
}
public function scopeDecrementUserColumn($query, $column)
{
$query = $query->whereHas('company', function ($company) {
$company->where('id', (new User())->authUserCompanyId());
})->first();
switch ($column) {
case 'uncompleted_replies':
$query->decrement('uncompleted_replies');
break;
}
if ($query->uncompleted_replies < 1) {
$query->add_more = 0;
$query->save();
}
}
public function scopeDecrementResolvedIssues($query)
{
$query = $query->whereHas('company', function ($company) {
$company->where('id', (new User())->authUserCompanyId());
})->first();
$query->decrement('resolved_issues');
}
public function scopeGetUserEmployeeId($query)
{
$query = $query->whereHas('roles', function ($q) {
$q->where('name', 'employee');
})->get();
$query = $query->pluck('id');
return $query;
}
public function sendSurvey($query)
{
$users = User::get();
foreach ($users as $user) {
if ($user->employees >= 5) {
// Get all employees where company is equal to $this->user
$userId = UserCompany::where('company_id', $user->company->id)->pluck('user_id');
}
}
}
public function scopeGetCompanyId($query, $userId)
{
$query = $query->find($userId)->userCompany->company_id;
return $query;
}
public function scopeGetSurveyCompleted($query)
{
$users = User::whereHas('roles', function ($role) {
$role->where('name', 'admin');
});
}
public function scopeGetCurrentSurveyDetails($query, $request = null)
{
$companyId = null;
$userAnswerFilter = new UsersAnswer();
if (!is_null($request)) {
// this is checking request parameters from super admin's vibe monitor
if (isset($request['id'])) {
$user = $query->find($request['id']);
} else {
$user = $query->find(auth()->id());
}
} else {
$user = $query->find(auth()->id());
}
if ($user->role_name == 'admin') {
$companyId = $user->company->id;
} elseif ($user->role_name == 'manager') {
$companyId = $user->userCompany->company_id;
}
$employeeCount = UserCompany::where('company_id', $companyId)
->where('role_name', 'employee')
->where('last_login_at', '!=', null);
$surveyCompleted = UserCompany::where('company_id', $companyId)
->where('role_name', 'employee')
->where('survey_completed', true);
$userAnswerFilter->filter($request, $surveyCompleted);
$userAnswerFilter->filter($request, $employeeCount);
$surveyCompleted = $surveyCompleted->count();
$employeeCount = $employeeCount->count();
if ($surveyCompleted > 0) {
$completionPercentage = round(($surveyCompleted / $employeeCount) * 100);
} else {
$completionPercentage = 0;
}
// date_default_timezone_set($user->timezone);
$now = Carbon::now();
$start = Carbon::parse($user->current_survey_date);
$end = Carbon::parse($user->current_survey_date)->next(Carbon::TUESDAY)->endOfDay();
// $end = $user->next_survey_date;
// $surveyStarts = Carbon::parse($start);
$surveyStarts = Carbon::parse($start)->format('Y-m-d');
// $surveyEnds = Carbon::parse($end);
$surveyEnds = Carbon::parse($end)->format('Y-m-d');
$now = Carbon::parse($now);
// $start = Carbon::parse($start);
// $end = Carbon::parse($end);
$diff = $end->diffInDays($now);
$status = $diff > 1 ? ('(' . $diff . ' days left)') : ('(' . $diff . ' day left)');
// $start = Carbon::parse($start)->isoFormat('LL');
// $end = Carbon::parse($end)->isoFormat('LL');
return [
'surveyId' => $user->current_survey_id,
'employeeCount' => $employeeCount,
'surveyCompleted' => $surveyCompleted,
'completionPercentage' => $completionPercentage,
'status' => $status,
'difference' => $diff,
'start' => $start->isoFormat('LL'),
'end' => $end->isoFormat('LL'),
'surveyStarts' => $surveyStarts,
'surveyEnds' => $surveyEnds
];
}
public function scopeGetUpcomingSurveyDetails($query, $userId = null)
{
$uId = $userId ?? auth()->id();
$auth = $query->find($uId);
// $surveyStarts = Carbon::createFromFormat('m-d-Y', $auth->next_survey_date);
$surveyStarts = Carbon::parse($auth->next_survey_date);
// Set survey ends base on account owner survey frequency setting
if ($auth->account->survey_frequency == 'every_week_wednesday') {
// $surveyEnds = $surveyStarts->addDays(7)->format('m-d-Y');
$surveyEnds = $surveyStarts->next(Carbon::TUESDAY)->endOfDay();
} else {
// $surveyEnds = $surveyStarts->addDays(14)->format('m-d-Y');
$surveyEnds = $surveyStarts->next(Carbon::TUESDAY)->next(Carbon::TUESDAY)->endOfDay();
}
// $now = Carbon::now()->format('m-d-Y');
$start = $auth->next_survey_date;
$end = $surveyEnds;
$now = Carbon::now();
$start = Carbon::parse($auth->next_survey_date);
$end = Carbon::parse($end);
$dateStartDbFormat = $auth->next_survey_date;
$dateEndDbFormat = $end;
$diff = $end->diffInDays($now);
$status = $diff > 1 ? ('(' . $diff . ' days left)') : ('(' . $diff . ' day left)');
$start = Carbon::parse($start)->isoFormat('LL');
$end = Carbon::parse($end)->isoFormat('LL');
return [
'surveyId' => $userId != null ? 'this is for email notification' : (new User())->authUserNextSurveyId(),
'status' => $status,
'start' => $start,
'dateStartDbFormat' => $dateStartDbFormat,
'dateEndDbFormat' => $dateEndDbFormat,
'end' => $end
];
}
public function scopeGetUpcomingSurveyDetails2($query)
{
$auth = $query->find(auth()->id());
$surveyStarts = Carbon::createFromFormat('m-d-Y', $auth->next_survey_date);
// Set survey ends base on account owner survey frequency setting
if ($auth->account->survey_frequency == 'every_week_wednesday') {
$surveyEnds = $surveyStarts->addDays(7)->format('m-d-Y');
} else {
$surveyEnds = $surveyStarts->addDays(14)->format('m-d-Y');
}
$now = Carbon::now()->format('m-d-Y');
$start = $auth->next_survey_date;
$end = $surveyEnds;
$now = Carbon::createFromFormat('m-d-Y', $now);
$start = Carbon::createFromFormat('m-d-Y', $start);
$end = Carbon::createFromFormat('m-d-Y', $end);
$dateStartDbFormat = $auth->next_survey_date;
$dateEndDbFormat = $end->format('m-d-Y');
$diff = $end->diffInDays($now);
$status = $diff > 1 ? ('(' . $diff . ' days left)') : ('(' . $diff . ' day left)');
$start = Carbon::parse($start, 'Asia/Manila')->isoFormat('LL');
$end = Carbon::parse($end, 'Asia/Manila')->isoFormat('LL');
return [
'surveyId' => (new User())->authUserNextSurveyId(),
'status' => $status,
'start' => $start,
'dateStartDbFormat' => $dateStartDbFormat,
'dateEndDbFormat' => $dateEndDbFormat,
'end' => $end
];
}
public function scopeGetPastSurveys($query)
{
$auth = $query->find(auth()->id());
$currentSurveyDate = Carbon::createFromFormat('m-d-Y', $auth->current_survey_date);
}
public function scopeAccountNotificationsSchedule($query, $schedule)
{
$users = $query->where('email_verified_at', '!=', null)->where('active', 1)->get();
foreach ($users as $user) {
$notification = $user->account->notifications['new_message'] ?? null;
if ($notification) {
$frequency = null;
switch ($notification) {
case 'every_10_minutes':
$frequency = 'everyTenMinutes';
break;
case '1x_per_hour':
$frequency = 'hourly';
break;
case '1x_per_day':
$frequency = 'daily';
break;
default:
break;
}
if ($user->total_replies != $user->new_messages_notification) {
$schedule->call(function () use ($user, $frequency) {
$language = $user->language;
$newMessages = $user->new_messages_notification;
$totalReply = $user->total_replies;
if ($newMessages > 1) {
$newMessages = $totalReply - $newMessages;
} else {
$newMessages = $user->total_replies;
}
if ($user->account->language_setting) {
$language = Language::find($user->account->language_setting)->language;
}
/** this should have job to avoid rapid sending of email that spikes email service provider */
Mail::to($user)->locale($language)->send(new \App\Mail\SendNewMessagesNotification($user, $newMessages));
$user->new_messages_notification = $user->total_replies;
$user->save();
})->$frequency();
}
}
}
}
}
I'm on Prestashop 1.7.6. I made a simple test module for adding a custom carrier and manage it programmatically.
Everything works well during checkout: I see new carrier with the correct cost, if I select it the total of cart is correct! (the shipping cost is added).
After choosing the payment method and confirming the order (and I'm redirected to order confirmation page), the shipping costs disappear: is always free shipping!
I do not understand why..
I report the code of this test:
<?php
if (!defined('_PS_VERSION_')) {
exit;
}
class TxShipping extends CarrierModule
{
const PREFIX = 'tx_';
public $id_carrier;
private $loopCount = 0;
private $shipCost = 0;
protected $_hooks = array(
'actionCarrierUpdate',
'displayOrderConfirmation',
);
protected $_carriers = array(
//"Public carrier name" => "technical name",
'My new carrier' => 'txshipping',
);
public function __construct()
{
$this->name = 'txshipping';
$this->tab = 'shipping_logistics';
$this->version = '1.0.0';
$this->author = 'Gerry';
$this->need_instance = 0;
$this->ps_versions_compliancy = [
'min' => '1.7.1.0',
'max' => _PS_VERSION_
];
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l('Tx Shipping');
$this->description = $this->l('manage shipping costs');
$this->confirmUninstall = $this->l('Are you sure you want to uninstall?');
if (!Configuration::get('TXSHIPPING_NAME')) {
$this->warning = $this->l('No name provided');
}
}
public function getTemplate($area, $file)
{
return 'views/templates/' . $area . '/' . $file;
}
//-------------------------------------------------
// Hooks
//-------------------------------------------------
public function hookActionCarrierUpdate($params)
{
if ($params['carrier']->id_reference == Configuration::get(self::PREFIX . 'fcd_reference')) {
Configuration::updateValue(self::PREFIX . 'fcd', $params['carrier']->id);
}
}
public function getOrderShippingCost($params = null, $shipping_cost = 0) {
$curPage = $this->context->controller->php_self;
/* using test on which page is running cause the following code is always executed (even if is loading home page!?)
I don't understand why */
if ($curPage == "order") {
$this->loopCount++; // attempt for not to run the same code over and over.. but it doesn't work very well
if ($this->loopCount == 1) {
$this->shipCost = 77;
/*
$address = new Address($params->id_address_delivery);
$cap = $address->postcode;
$curID = $this->id_carrier; */
}
return floatval($this->shipCost);
} elseif ($curPage == "order-confirmation") {
$test = 76; // for simple test
return floatval($test);
} else {
if ($curPage != "pagenotfound") {
$this->loopCount = 0;
$this->shipCost = 0;
}
}
}
public function getOrderShippingCostExternal($params){
//return 999; costi spedizione
return $this->getOrderShippingCost($params, 0);
}
//-------------------------------------------------
// Setup
//-------------------------------------------------
public function install()
{
if (parent::install()) {
foreach ($this->_hooks as $hook) {
if (!$this->registerHook($hook)) {
return false;
}
}
if (!$this->createCarriers()) {
return false;
}
return true;
}
return false;
}
public function uninstall()
{
if (parent::uninstall()) {
foreach ($this->_hooks as $hook) {
if (!$this->unregisterHook($hook)) {
return false;
}
}
if (!$this->deleteCarriers()) {
return false;
}
return true;
}
return false;
}
//-------------------------------------------------
// Funzioni private
//-------------------------------------------------
protected function createCarriers()
{
foreach ($this->_carriers as $key => $value) {
//Create own carrier
$carrier = new Carrier();
$carrier->name = $key;
$carrier->id_tax_rules_group = 0;
$carrier->active = 1;
$carrier->deleted = 0;
foreach (Language::getLanguages(true) as $language)
$carrier->delay[(int)$language['id_lang']] = 'Delay [1-2 days]';
$carrier->shipping_handling = false;
$carrier->range_behavior = 0;
$carrier->is_module = true;
$carrier->shipping_external = true;
$carrier->external_module_name = $this->name;
$carrier->need_range = true;
if ($carrier->add()) {
$groups = Group::getGroups(true);
foreach ($groups as $group) {
Db::getInstance()->autoExecute(_DB_PREFIX_ . 'carrier_group', array(
'id_carrier' => (int) $carrier->id,
'id_group' => (int) $group['id_group']
), 'INSERT');
}
$rangePrice = new RangePrice();
$rangePrice->id_carrier = $carrier->id;
$rangePrice->delimiter1 = '0';
$rangePrice->delimiter2 = '1000000';
$rangePrice->add();
$rangeWeight = new RangeWeight();
$rangeWeight->id_carrier = $carrier->id;
$rangeWeight->delimiter1 = '0';
$rangeWeight->delimiter2 = '1000000';
$rangeWeight->add();
$zones = Zone::getZones(true);
foreach ($zones as $z) {
Db::getInstance()->autoExecute(_DB_PREFIX_ . 'carrier_zone',
array('id_carrier' => (int) $carrier->id, 'id_zone' => (int) $z['id_zone']), 'INSERT');
Db::getInstance()->autoExecuteWithNullValues(_DB_PREFIX_ . 'delivery',
array('id_carrier' => $carrier->id, 'id_range_price' => (int) $rangePrice->id, 'id_range_weight' => NULL, 'id_zone' => (int) $z['id_zone'], 'price' => '0'), 'INSERT');
Db::getInstance()->autoExecuteWithNullValues(_DB_PREFIX_ . 'delivery',
array('id_carrier' => $carrier->id, 'id_range_price' => NULL, 'id_range_weight' => (int) $rangeWeight->id, 'id_zone' => (int) $z['id_zone'], 'price' => '0'), 'INSERT');
}
copy(dirname(__FILE__) . '/views/img/carrier.jpg', _PS_SHIP_IMG_DIR_ . '/' . (int) $carrier->id . '.jpg');
Configuration::updateValue(self::PREFIX . $value, $carrier->id);
Configuration::updateValue(self::PREFIX . $value . '_reference', $carrier->id);
}
}
return true;
}
protected function deleteCarriers()
{
foreach ($this->_carriers as $value) {
$tmp_carrier_id = Configuration::get(self::PREFIX . $value);
$carrier = new Carrier($tmp_carrier_id);
$carrier->delete();
}
return true;
}
}
Im my opinion it has something to do with your $curPage
I'd go for this if instead:
if ($this->context->controller instanceof CartController || $this->context->controller instanceof OrderController) {
I don't understand this part of code:
} elseif ($curPage == "order-confirmation") {
why would you do something different on real order-confirmation page where order is already placed?
This is where i get the error:
$data = Excel::import($path, function($reader) {})->get();
I changed the load() to import(). I want to run this code in Laravel 6, but version 3 of MaatWebsiteExcel does not support load().
I've been searching for solutions, yet i cant find any....
This is my controller:
namespace App\Http\Controllers;
use App\Contact;
use App\CsvData;
use App\Http\Requests\CsvImportRequest;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use Session;
use DB;
class ImportController extends Controller
{
public function getImport()
{
return view('import');
}
function parseImport(CsvImportRequest $request)
{
$path = $request->file('csv_file')->getRealPath();
if ($request->has('header')) {
$data = Excel::import($path, function($reader) {})->get();
} else {
$data = array_map('str_getcsv', file($path));
}
if (count($data) > 0) {
if ($request->has('header')) {
$csv_header_fields = [];
foreach ($data[0] as $key => $value) {
$csv_header_fields[] = $key;
}
}
$csv_data = array_slice($data, 0, 2);
$credentials = $request->file('csv_file')->getClientOriginalName();
$filename = CsvData::all('csv_filename');
if(CsvData::where('csv_filename', '=' ,$credentials)->exists()){
return redirect()->back()->with('alert', 'This specific file has already been imported!');
}
else{
$csv_data_file = CsvData::create([
'csv_filename' => $request->file('csv_file')->getClientOriginalName(),
'csv_header' => $request->has('header'),
'csv_data' => json_encode($data)
]);
}
}
else {
return redirect()->back();
}
return view('import_fields', compact( 'csv_header_fields', 'csv_data', 'csv_data_file'));
}
public function processImport(Request $request)
{
$data = CsvData::find($request->csv_data_file_id);
$csv_data = json_decode($data->csv_data, true);
if(CsvData::where('csv_data', '=' ,$csv_data)->exists()){
return redirect()->back()->with('alert', 'This file has already been imported!');
}
else{
foreach ($csv_data as $row) {
$contact = new Contact();
foreach (config('app.db_fields') as $index => $field) {
if ($data->csv_header) {
$contact->$field = $row[$request->fields[$field]];
} else {
$contact->$field = $row[$request->fields[$index]];
}
}
foreach($contact as $contacts){
$contact->posted_by = $contacts->posted_by;
$contact->employer = $contacts->employer;
$contact->address = $contacts->address;
$contact->barangay = $contacts->barangay;
$contact->citymunicipality = $contacts->citymunicipality;
$contact->province = $contacts->province;
$contact->region = $contacts->region;
$contact->position = $contacts->position;
$contact->job_description = $contacts->job_description;
$contact->salary = $contacts->salary;
$contact->count = $contacts->count;
$contact->work_location = $contacts->work_location;
$contact->nature_of_work = $contacts->nature_of_work;
$contact->min_work_exp_mos = $contacts->min_work_exp_mos;
$contact->min_educ_level = $contacts->min_educ_level;
$contact->coursemajor = $contacts->coursemajor;
$contact->min_age = $contacts->min_age;
$contact->max_age = $contacts->max_age;
$contact->min_height = $contacts->min_height;
$contact->sex = $contacts->sex;
$contact->civil_status = $contacts->civil_status;
$contact->other_qualifications = $contacts->other_qualifications;
$contact->remarks = $contacts->remarks;
$contact->accept_disability = $contacts->accept_disability;
$contact->date_posted = $contacts->date_posted['date'];
$contact->valid_until = $contacts->valid_until['date'];
$contact->date_created = $contacts->date_created['date'];
$contact->last_modified_by = $contacts->last_modified_by['date'];
$contact->date_last_modified = $contacts->date_last_modified['date'];
}
$contact->save();
return view('import_success');
}
}
}
}```
The first parameter of the import() method is not the path to the file anymore in Laravel 3.1, but the class name of the Import file you have to create.
You need to follow below steps to use import method
Step1: Create Import File using below command.
php artisan make:import CsvImport
Step2: Inside CsvImport make changes like this:
namespace App\Imports;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
class CsvImport implements ToCollection
{
public function collection(Collection $rows)
{
return $rows; //add this line
}
}
Step3: In Controller make changes like this:
$path = $request->file('csv_file')->getRealPath();
$rows = Excel::import(new CsvImport, $path);
Reference:
https://docs.laravel-excel.com/3.1/imports/basics.html
I need only those columns after specific indexing, which I consider practically the same use case as described in the question at the top of this page. I propose the following as solution.
$fileArr = (new BulkSampleImport)->toArray($request->file);
This file is the database ID information all the fields and went and came to a Blade, I want to an ID information entered in the same panel Blade I send my face.
class DataGrid extends DataSet
{
protected $fields = array();
/** #var Column[] */
public $columns = array();
public $headers = array();
public $rows = array();
public $output = "";
public $attributes = array("class" => "table");
public $checkbox_form = false;
protected $row_callable = array();
/**
* #param string $name
* #param string $label
* #param bool $orderby
*
* #return Column
*/
public function add($name, $label = null, $orderby = false)
{
$column = new Column($name, $label, $orderby);
$this->columns[$column->name] = $column;
if (!in_array($name,array("_edit"))) {
$this->headers[] = $label;
}
if ($orderby) {
$this->addOrderBy($column->orderby_field);
}
return $column;
}
//todo: like "field" for DataForm, should be nice to work with "cell" as instance and "row" as collection of cells
public function build($view = '')
{
($view == '') and $view = 'rapyd::datagrid';
parent::build();
Persistence::save();
foreach ($this->data as $tablerow) {
$row = new Row($tablerow);
foreach ($this->columns as $column) {
$cell = new Cell($column->name);
$sanitize = (count($column->filters) || $column->cell_callable) ? false : true;
$value = $this->getCellValue($column, $tablerow, $sanitize);
$cell->value($value);
$cell->parseFilters($column->filters);
if ($column->cell_callable) {
$callable = $column->cell_callable;
$cell->value($callable($cell->value, $tablerow));
}
$row->add($cell);
}
if (count($this->row_callable)) {
foreach ($this->row_callable as $callable) {
$callable($row);
}
}
$this->rows[] = $row;
}
$routeParamters = \Route::current()->parameters();
return \View::make($view, array('dg' => $this, 'buttons'=>$this->button_container, 'label'=>$this->label,
'current_entity' => $routeParamters['entity']));
}
public function buildCSV($file = '', $timestamp = '', $sanitize = true,$del = array())
{
$this->limit = null;
parent::build();
$segments = \Request::segments();
$filename = ($file != '') ? basename($file, '.csv') : end($segments);
$filename = preg_replace('/[^0-9a-z\._-]/i', '',$filename);
$filename .= ($timestamp != "") ? date($timestamp).".csv" : ".csv";
$save = (bool) strpos($file,"/");
//Delimiter
$delimiter = array();
$delimiter['delimiter'] = isset($del['delimiter']) ? $del['delimiter'] : ';';
$delimiter['enclosure'] = isset($del['enclosure']) ? $del['enclosure'] : '"';
$delimiter['line_ending'] = isset($del['line_ending']) ? $del['line_ending'] : "\n";
if ($save) {
$handle = fopen(public_path().'/'.dirname($file)."/".$filename, 'w');
} else {
$headers = array(
'Content-Type' => 'text/csv',
'Pragma'=>'no-cache',
'"Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
'Content-Disposition' => 'attachment; filename="' . $filename.'"');
$handle = fopen('php://output', 'w');
ob_start();
}
fputs($handle, $delimiter['enclosure'].implode($delimiter['enclosure'].$delimiter['delimiter'].$delimiter['enclosure'], $this->headers) .$delimiter['enclosure'].$delimiter['line_ending']);
foreach ($this->data as $tablerow) {
$row = new Row($tablerow);
foreach ($this->columns as $column) {
if (in_array($column->name,array("_edit")))
continue;
$cell = new Cell($column->name);
$value = str_replace('"', '""',str_replace(PHP_EOL, '', strip_tags($this->getCellValue($column, $tablerow, $sanitize))));
$cell->value($value);
$row->add($cell);
}
if (count($this->row_callable)) {
foreach ($this->row_callable as $callable) {
$callable($row);
}
}
fputs($handle, $delimiter['enclosure'] . implode($delimiter['enclosure'].$delimiter['delimiter'].$delimiter['enclosure'], $row->toArray()) . $delimiter['enclosure'].$delimiter['line_ending']);
}
fclose($handle);
if ($save) {
//redirect, boolean or filename?
} else {
$output = ob_get_clean();
return \Response::make(rtrim($output, "\n"), 200, $headers);
}
}
protected function getCellValue($column, $tablerow, $sanitize = true)
{
//blade
if (strpos($column->name, '{{') !== false ||
strpos($column->name, '{!!') !== false) {
if (is_object($tablerow) && method_exists($tablerow, "getAttributes")) {
$fields = $tablerow->getAttributes();
$relations = $tablerow->getRelations();
$array = array_merge($fields, $relations) ;
$array['row'] = $tablerow;
} else {
$array = (array) $tablerow;
}
$value = $this->parser->compileString($column->name, $array);
//eager loading smart syntax relation.field
} elseif (preg_match('#^[a-z0-9_-]+(?:\.[a-z0-9_-]+)+$#i',$column->name, $matches) && is_object($tablerow) ) {
//switch to blade and god bless eloquent
$_relation = '$'.trim(str_replace('.','->', $column->name));
$expression = '{{ isset('. $_relation .') ? ' . $_relation . ' : "" }}';
$fields = $tablerow->getAttributes();
$relations = $tablerow->getRelations();
$array = array_merge($fields, $relations) ;
$value = $this->parser->compileString($expression, $array);
//fieldname in a collection
} elseif (is_object($tablerow)) {
$value = #$tablerow->{$column->name};
if ($sanitize) {
$value = $this->sanitize($value);
}
//fieldname in an array
} elseif (is_array($tablerow) && isset($tablerow[$column->name])) {
$value = $tablerow[$column->name];
//none found, cell will have the column name
} else {
$value = $column->name;
}
//decorators, should be moved in another method
if ($column->link) {
if (is_object($tablerow) && method_exists($tablerow, "getAttributes")) {
$array = $tablerow->getAttributes();
$array['row'] = $tablerow;
} else {
$array = (array) $tablerow;
}
$value = ''.$value.'';
}
if (count($column->actions)>0) {
$key = ($column->key != '') ? $column->key : $this->key;
$keyvalue = #$tablerow->{$key};
$routeParamters = \Route::current()->parameters();
$value = \View::make('rapyd::datagrid.actions', array('uri' => $column->uri, 'id' => $keyvalue, 'actions' => $column->actions,
'current_entity' => $routeParamters['entity']));
}
return $value;
}
public function getGrid($view = '')
{
$this->output = $this->build($view)->render();
return $this->output;
}
public function __toString()
{
if ($this->output == "") {
//to avoid the error "toString() must not throw an exception"
//http://stackoverflow.com/questions/2429642/why-its-impossible-to-throw-exception-from-tostring/27307132#27307132
try {
$this->getGrid();
}
catch (\Exception $e) {
$previousHandler = set_exception_handler(function (){ });
restore_error_handler();
call_user_func($previousHandler, $e);
die;
}
}
return $this->output;
}
public function edit($uri, $label='Edit', $actions='show|modify|delete', $key = '')
{
return $this->add('_edit', $label)->actions($uri, explode('|', $actions))->key($key);
}
public function getColumn($column_name)
{
if (isset($this->columns[$column_name])) {
return $this->columns[$column_name];
}
}
public function addActions($uri, $label='Edit', $actions='show|modify|delete', $key = '')
{
return $this->edit($uri, $label, $actions, $key);
}
public function row(\Closure $callable)
{
$this->row_callable[] = $callable;
return $this;
}
protected function sanitize($string)
{
$result = nl2br(htmlspecialchars($string));
return Config::get('rapyd.sanitize.num_characters') > 0 ? str_limit($result, Config::get('rapyd.sanitize.num_characters')) : $result;
}
public function rowCount()
{
return count($this->rows);
}
}
This is the source of a rapyd-laravel widget/package, not a custom code.
According to DataGrid/DataSet documentation, you can use many sources:
https://github.com/zofe/rapyd-laravel/wiki/DataSet
DataSet/DataGrid are presenters, you can retrieve all data of your data source using
{{ $item->field }} or {{ $row->field }} respectively
See the docs please
https://github.com/zofe/rapyd-laravel/wiki