Can not use seession laravel - laravel

I initialize session('idUser') on successful login. But it is always null when using http get.And Auth::id() is always null as well.
class CartService {
public function getAll($orderBys = [], $limit = 2) {
$idCurrent = session('idUser'); // => null
//$idCurrent = Auth::id(); => null
$query = Cart::query() -> where('user_id',$idCurrent);
if($orderBys){
$query->orderBy($orderBys['column'], $orderBys['sort']);
}
return $query-> paginate($limit);
}
}
//Call API (127.0.0.1:8000/api/cart)
public function index(Request $request)
{
$carts = Http::get("http://127.0.0.1:8000/api/cart");
$carts = json_decode($carts, true);
$cartArr = $carts['cartArr'];
//convert
$cart = array();
for($i = 0; $i < count($cartArr); $i++)
{
$object = new Cart();
foreach ($cartArr[$i] as $key => $value)
{
$object->$key = $value;
}
array_push($cart,$object);
}
dd($cart); // => result = []
}

Related

Requesting solution for laravel 8 project

I'm an elementary web developer, I'm facing a problem. Please help me solve this. I'm creating both row and column dynamic. for save() is fine. But for update, only name is updated and other item
quantities cannot. Here is my codes.
//for save()
public function stockAdd(Request $request)
{
$validator = validator(request()->all(), ['stock_name' => 'required']);
if($validator->fails()) {
return back()->withErrors($validator);
}
$user_id = Auth::user()->user_id;
$stock_id = random_int(100000, 999999);
$stocks = new Stocks();
$stocks->stock_id = $stock_id;
$stocks->owner_id = $user_id;
$stocks->stock_name = request()->stock_name;
$stocks->my_stock = 0;
$stocks->disable = 0;
$stocks->save();
$brands = Brands::all();
$products = Products::all();
foreach ($brands as $brand){
foreach ($products as $product){
if($product['brand_id'] == $brand['id']){
$product_id = $product->product_id;
$stockitems = new StockItems();
$stockitems->stock_id = $stock_id;
$stockitems->product_id = $product->product_id;
$stockitems->owner_id = $user_id;
if(request()->$product_id > 0){
$stockitems->count = request()->$product_id;
}else{
$stockitems->count = 0;
}
$stockitems->save();
}
}
}
return redirect()->back()->with('successAddMsg','Successfully Added');
}
//for update()
public function stockUpdate(Request $request, $id)
{
$validator = validator(request()->all(), ['stock_name' => 'required']);
if($validator->fails()) {
return back()->withErrors($validator);
}
$stock = Stocks::findOrFail($id);
$stock->stock_name = request()->stock_name;
$stock->my_stock = 0;
$stock->disable = 0;
$stock->update();
$brands = Brands::all();
$products = Products::all();
foreach ($brands as $brand){
foreach ($products as $product){
if($product['brand_id'] == $brand['id']){
$product_id = $product->product_id;
//dd($product_id);
$stockitemitems = DB::table("stock_items")->select("*")->where("owner_id",Auth::user()->user_id)->where("stock_id",$stock->stock_id)->get();
$stockitems->count = $request->input($product_id);
$stockitems->update();
}
}
}
return redirect(route('user.stock-list'))->with('successAddMsg','Successfully Added');
}
The problem shows like this "Creating default object from empty value"

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?

PhpStorm cannot track some file changes

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

Picture not uploading to database but saving in folder

public function array_from_post($fields) {
$data = array();
foreach ($fields as $field) {
$data[$field] = $this->input->post($field);
$data['category_id'] = $this->input->post('category');
public function save($data, $id = NULL) {
// Set timestamps
if ($this->_timestamps == TRUE) {
$now = date('Y-m-d H:i:s');
$id || $data['created'] = $now;
$data['modified'] = $now;
}
// Insert
if ($id === NULL) {
!isset($data[$this->_primary_key]) || $data[$this->_primary_key] = NULL;
$this->db->set($data);
$this->db->insert($this->_table_name);
$id = $this->db->insert_id();
}
// Update
else {
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->set($data);
$this->db->where($this->_primary_key, $id);
$this->db->update($this->_table_name);
}
return $id;
}
On save this code returns column picture cannot be null. When i do the direct method without using the method array_from_post(), data is saved in the database but i can not save a post to be published at a future date.

Get the information you entered to ID

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

Resources