How to set hit counter in yii - php

I'd like to make a hit counter that will add the count when user enter the website through their ip address. This is my code:
for views:
<?php echo number_format(Visitor::model()->GetAll('portal')); ?>
this is my model:
public function attributeLabels() {
return array(
'id' => 'ID',
'web' => 'Web',
'dtvisit' => 'Dtvisit',
'total' => 'Total',
);
}
public function AddVisitor($web) {
date_default_timezone_set('Asia/Kuala_Lumpur');
$today = date('Y-m-d');
$model = $this->findByAttributes(array('dtvisit' => $today, 'web' => $web));
if (sizeof($model) > 0) {
//update
$model2 = $this->findByPk($model->id);
$model2->total = (1 + $model->total);
$model2->save();
} else {
//add new
$model2 = new Visitor;
$model2->web = $web;
$model2->dtvisit = $today;
$model2->total = 1;
$model2->save();
}
}
public function GetAll($web) {
date_default_timezone_set('Asia/Kuala_Lumpur');
$model = $this->findAll(array("condition" => "web='$web'"));
$total = 0;
if (sizeof($model) > 0) {
foreach ($model as $row) {
$total+= (int) $row->total;
}
}
return $total;
}
CUrrently, the total will add everytime I refresh or click any links on my website. How to make it add the total only when new user enter the website. Thank you

I think you should use Params for passing value
public function GetAll($web) {
date_default_timezone_set('Asia/Kuala_Lumpur');
$model = $this->findAll(array("condition" => "web=':web'",
'params' => array(:web=$web)));
$total = 0;
if (sizeof($model) > 0) {
foreach ($model as $row) {
$total+= (int) $row->total;
}
}
return $total;
}

Related

How to access array values in laravel

This method i am using for storing currentTime in database using ajax call and its working
public function saveTime(Request $request, $lession_id){
$user = Auth::user();
if($user === null){
return response()->json(['message' => 'User not authenticated', 404]);
}
$video = \App\Lession::where('id',$lession_id)->first();
$lesson_id = $request->lession_id;
$progress = $request->time;
//save them somewhere
$watch_history = $user->watch_history;
$watch_history_array = array();
if ($watch_history == '') {
array_push($watch_history_array, array('lession_id' => $lesson_id, 'progress' => $progress));
} else {
$founder = false;
$watch_history_array = json_decode($watch_history, true);
for ($i = 0; $i < count($watch_history_array); $i++) {
$watch_history_for_each_lesson = $watch_history_array[$i];
if ($watch_history_for_each_lesson['lession_id'] == $lesson_id) {
$watch_history_for_each_lesson['progress'] = $progress;
$watch_history_array[$i]['progress'] = $progress;
$founder = true;
}
}
if (!$founder) {
array_push($watch_history_array, array('lession_id' => $lesson_id, 'progress' => $progress));
}
}
$data['watch_history'] = json_encode($watch_history_array);
$check = User::where('id',$user->id)->update(['watch_history' => $watch_history_array]);
return response()->json(['message' => 'Time saved', 200]);//send http response as json back to the ajax call
}
But when I use this another method to get the time back for playback it's getting the array inside an array
public function getTime(Request $request, $lession_id){
$user = Auth::user();
if($user === null){
return response()->json(['message' => 'User not authenticated', 403]);
}
$user_video = User::where('id',$user->id)->first();
$array = $user_video->watch_history;
foreach ($array as $key => $value) {
echo $check;
}
}
My current Output in a database is as follows
[{"lession_id":"157","progress":"71.449464"},{"lession_id":"156","progress":"92.113123"}]
So help me to get the values out of that for each lession id

I want to replicate one row into 365 row in one table in Laravel

I want to save the same data with 365 records within one table. I'm new to Laravel.
I've tried with replicate() but was unsuccessful. I tried this on the Apache server and used Laravel5.7.
my controller
public function price_save(Request $request) {
$price=new Price();
$price->price=$request->price;
$price->extra_bed=$request->extra_bed;
$price->room_id=$request->room;
$id=$request->room;
$price = Price::find($id);
if(null !== $price){
$new = $price->replicate();
if(null !== $new){
$new->push();
// $price->save();
}
I am NOT sure about your code, But you can customize it as per your needs, To just get idea :
$model = User::find($id);
$model->load('invoices');
$newModel = $model->replicate();
$newModel->push();
foreach($model->getRelations() as $relation => $items){
foreach($items as $item){
unset($item->id);
$newModel->{$relation}()->create($item->toArray());
}
}
Credits
public function price_save(Request $request, int $id)
{
if ($id > 365) {
return;
}
$price = new Price();
$price->price = $request->price;
$price->extra_bed = $request->extra_bed;
$price->room_id = $request->room;
$price->save();
$existing = Price::find($request->room);
if ($existing) {
$request = $request->replace([
'price' => $price->price,
'extra_bed' => $price->extra_bed,
'room_id' => $price->room,
]);
}
return price_save($request, $id++);
}

Yii2 getting the url ID in redirect. in create action

like I have a view index.php(Gridview)- linked to a Menu Manage Instructor.
from there I click on edit for a specific instructor.
The URL I get is like:
admin/user/update-instructor?id=11
In this page I have multiple tabs, one tab is instructor_schedule, which is again a grid view with add records button on top.
I can add records clicking on add record without any issue.
My problem is now I want the form page redirect back to the page
admin/user/update-instructor?id=11
How I can achieve that?
I have tried like:
return $this->redirect(['user/update-instructor','id' => $model->id]);
and
return $this->redirect(['user/update-instructor','id' => $model->instructor_id]);
but I am getting the error missing information id.
Thanks.
action Create(ClassDurationController):
public function actionCreate() {
$model = new ClassDuration();
$count = count(Yii::$app->request->post('ClassDuration', []));
$classdurations[] =new ClassDuration();
for($i = 1; $i < $count; $i++) {
$classdurations[] = new ClassDuration();
}
//if ($model->load(Yii::$app->request->post()) && $model->save()) {
if (Model::loadMultiple($classdurations, Yii::$app->request->post()) && Model::validateMultiple($classdurations)) {
foreach ($classdurations as $classduration) {
// var_dump($classdurations);
$classduration->instructor_id=$_POST['ClassDuration'][0]['instructor_id'];
$classduration->save(false);
}
Yii::$app->getSession()->setFlash('successClass');
//return $this->redirect(['view', 'id' => $model->id]);
return $this->redirect(['user/update-instructor','id' => $model->id]);
}
return $this->render('create', [
'model' => $model,
'classdurations' => $classdurations,
]);
}
Action Update(ClassDurationController):
public function actionUpdate($id,$tab='information') {
$model = $this->findModel($id);
$wd_instructor = ClassDuration::find('instructor_id')->where(['id'=>$id])->One();
$wd_instructor_id = $wd_instructor->instructor_id;
$classdurations = ClassDuration::find()->where(['instructor_id'=>$wd_instructor_id])->all();
if (Model::loadMultiple($classdurations, Yii::$app->request->post()) && Model::validateMultiple($classdurations)) {
foreach($classdurations as $classduration){
$classduration->location_id=$_POST['ClassDuration'][0]['location_id'];
$classduration->save(false);
}
Yii::$app->getSession()->setFlash('successClass');
// return $this->redirect(['view', 'id' => $model->id]);
return $this->redirect(['user/update-instructor', 'id' => $model->instructor_id, 'tab' => 'instructor_schedule']);
}
return $this->render('update', [
'model' => $model,
'workingdays' => $classdurations,
]);
}
ActionUpdateInstructor:
public function actionUpdateInstructor($id,$tab='information') {
$model = User::findOne($id);
$uploadPath = 'web/instructor/' . $id;
if (!file_exists($uploadPath)) {
mkdir($uploadPath);
}
$profile = Instructor::find()->where(['user_id' => $id])->one();
if ($profile) {
$instructor_profile = $profile;
} else {
$instructor_profile = new Instructor;
$instructor_profile->user_id = $id;
}
if ($id == 1) {
$cls = 'hide';
} else {
$cls = '';
}
$title = "Update";
$modelsRest = $model->rest;
$modelsBreakTime = $model->breakTime;
if (Yii::$app->request->isAjax && $model->load($_POST)) {
Yii::$app->response->format = 'json';
return \yii\bootstrap\ActiveForm::validate($model);
}
if (Yii::$app->request->isAjax && $instructor_profile->load($_POST)) {
Yii::$app->response->format = 'json';
return \yii\bootstrap\ActiveForm::validate($instructor_profile);
}
if ($model->load(Yii::$app->request->post()) && $instructor_profile->load(Yii::$app->request->post())) {
$oldIDs = ArrayHelper::map($modelsRest, 'id', 'id');
$modelsRest = Model::createMultiple(RestDays::classname(), $modelsRest);
Model::loadMultiple($modelsRest, Yii::$app->request->post());
$deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelsRest, 'id', 'id')));
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ArrayHelper::merge(
ActiveForm::validateMultiple($modelsRest),
ActiveForm::validate($model),
ActiveForm::validate($instructor_profile)
);
}
if (trim($model->password) != '') {
$model->setPassword($model->password);
}
$model->username = $model->email;
$model->save();
if ($model->user_role != '') {
$assign = AuthAssignment::find()->where(['user_id' => $model->id])->One();
$assign->item_name = $model->user_role;
$assign->save();
}
$instructor_profile->file = UploadedFile::getInstance($instructor_profile, 'file');
$instructor_profile->user_id = $model->id;
if ($instructor_profile->file != '') {
$instructor_profile->instructor_image = time() . '.' . $instructor_profile->file->extension;
}
$instructor_profile->save(false);
if ($instructor_profile->file != '') {
$uploadPath = 'web/instructor/' . $instructor_profile->user_id;
if (!file_exists($uploadPath)) {
mkdir($uploadPath);
}
$instructor_profile->file->saveAs($uploadPath . '/' . $instructor_profile->instructor_image);
}
$valid = $model->validate();
$valid = Model::validateMultiple($modelsRest) && $valid;
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
if (!empty($deletedIDs)) {
RestDays::deleteAll(['id' => $deletedIDs]);
}
foreach ($modelsRest as $modelRests) {
$modelRests->instructor_id = $model->id;
if (!empty($modelRests->from_date) && !($flag = $modelRests->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
//return $this->redirect(['view-instructor', 'id' => $model->id]);
return $this->redirect(['instructor']);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
}
return $this->render('update_instructor', [
'model' => $model,
'modelsRest' => (empty($modelsRest)) ? [new RestDays] : $modelsRest,
'instructor_profile' => $instructor_profile,
'title' => $title,
'cls' => $cls,
]);
}
In your action Create(ClassDurationController) you assign to $model only
$model = new ClassDuration();
Maybe you should insert another variable to get id from parent or
return $this->redirect(['user/update-instructor','id' => $_POST['ClassDuration'][0]['instructor_id']]);

Laravel - Select box

I have the following select box which lists the all users. I need list users only which groupID is==3 How can I do that ?
Thanks in advance
<div class="form-group " >
<label for="Staff" class=" control-label col-md-4 text-left"> Staff </label>
<div class="col-md-7">
<select name='Staff' rows='5' id='Staff' class='select2 ' ></select>
</div>
<div class="col-md-1">
</div>
</div>
Controller
use App\Http\Controllers\controller; use App\Models\Adminorders; use Illuminate\Http\Request; use Illuminate\Pagination\LengthAwarePaginator as Paginator; use Validator, Input, Redirect ;
class AdminordersController extends Controller {
protected $layout = "layouts.main";
protected $data = array();
public $module = 'adminorders';
static $per_page = '10';
public function __construct()
{
parent::__construct();
$this->beforeFilter('csrf', array('on'=>'post'));
$this->model = new Adminorders();
$this->modelview = new \App\Models\Orderdetail();
$this->info = $this->model->makeInfo( $this->module);
$this->access = $this->model->validAccess($this->info['id']);
$this->data = array(
'pageTitle' => $this->info['title'],
'pageNote' => $this->info['note'],
'pageModule'=> 'adminorders',
'return' => self::returnUrl()
);
$this->data['subgrid'] = (isset($this->info['config']['subgrid']) ? $this->info['config']['subgrid'][0] : array());
}
public function getIndex( Request $request )
{
if($this->access['is_view'] ==0)
return Redirect::to('dashboard')
->with('messagetext', \Lang::get('core.note_restric'))->with('msgstatus','error');
$sort = (!is_null($request->input('sort')) ? $request->input('sort') : 'SiparisID');
$order = (!is_null($request->input('order')) ? $request->input('order') : 'asc');
// End Filter sort and order for query
// Filter Search for query
$filter = '';
if(!is_null($request->input('search')))
{
$search = $this->buildSearch('maps');
$filter = $search['param'];
$this->data['search_map'] = $search['maps'];
}
$page = $request->input('page', 1);
$params = array(
'page' => $page ,
'limit' => (!is_null($request->input('rows')) ? filter_var($request->input('rows'),FILTER_VALIDATE_INT) : static::$per_page ) ,
'sort' => $sort ,
'order' => $order,
'params' => $filter,
'global' => (isset($this->access['is_global']) ? $this->access['is_global'] : 0 )
);
// Get Query
$results = $this->model->getRows( $params );
// Build pagination setting
$page = $page >= 1 && filter_var($page, FILTER_VALIDATE_INT) !== false ? $page : 1;
$pagination = new Paginator($results['rows'], $results['total'], $params['limit']);
$pagination->setPath('adminorders');
$this->data['rowData'] = $results['rows'];
// Build Pagination
$this->data['pagination'] = $pagination;
// Build pager number and append current param GET
$this->data['pager'] = $this->injectPaginate();
// Row grid Number
$this->data['i'] = ($page * $params['limit'])- $params['limit'];
// Grid Configuration
$this->data['tableGrid'] = $this->info['config']['grid'];
$this->data['tableForm'] = $this->info['config']['forms'];
// Group users permission
$this->data['access'] = $this->access;
// Detail from master if any
// Master detail link if any
$this->data['subgrid'] = (isset($this->info['config']['subgrid']) ? $this->info['config']['subgrid'] : array());
// Render into template
return view('adminorders.index',$this->data);
}
function getUpdate(Request $request, $id = null)
{
if($id =='')
{
if($this->access['is_add'] ==0 )
return Redirect::to('dashboard')->with('messagetext',\Lang::get('core.note_restric'))->with('msgstatus','error');
}
if($id !='')
{
if($this->access['is_edit'] ==0 )
return Redirect::to('dashboard')->with('messagetext',\Lang::get('core.note_restric'))->with('msgstatus','error');
}
$row = $this->model->find($id);
if($row)
{
$this->data['row'] = $row;
} else {
$this->data['row'] = $this->model->getColumnTable('tb_orders');
}
$this->data['fields'] = \SiteHelpers::fieldLang($this->info['config']['forms']);
$relation_key = $this->modelview->makeInfo($this->info['config']['subform']['module']);
$this->data['accesschild'] = $this->modelview->validAccess($relation_key['id']);
$this->data['relation_key'] = $relation_key['key'];
$this->data['subform'] = $this->detailview($this->modelview , $this->info['config']['subform'] ,$id );
$this->data['id'] = $id;
return view('adminorders.form',$this->data);
}
public function getShow( Request $request, $id = null)
{
if($this->access['is_detail'] ==0)
return Redirect::to('dashboard')
->with('messagetext', \Lang::get('core.note_restric'))->with('msgstatus','error');
$row = $this->model->getRow($id);
if($row)
{
$this->data['row'] = $row;
$this->data['fields'] = \SiteHelpers::fieldLang($this->info['config']['grid']);
$this->data['id'] = $id;
$this->data['access'] = $this->access;
$this->data['subgrid'] = (isset($this->info['config']['subgrid']) ? $this->info['config']['subgrid'] : array());
$this->data['prevnext'] = $this->model->prevNext($id);
return view('adminorders.view',$this->data);
} else {
return Redirect::to('adminorders')->with('messagetext','Record Not Found !')->with('msgstatus','error');
}
}
function postSave( Request $request)
{
$rules = $this->validateForm();
$validator = Validator::make($request->all(), $rules);
if ($validator->passes()) {
$data = $this->validatePost('tb_adminorders');
$id = $this->model->insertRow($data , $request->input('SiparisID'));
$this->detailviewsave( $this->modelview , $request->all() ,$this->info['config']['subform'] , $id) ;
if(!is_null($request->input('apply')))
{
$return = 'adminorders/update/'.$id.'?return='.self::returnUrl();
} else {
$return = 'adminorders?return='.self::returnUrl();
}
// Insert logs into database
if($request->input('SiparisID') =='')
{
\SiteHelpers::auditTrail( $request , 'New Data with ID '.$id.' Has been Inserted !');
} else {
\SiteHelpers::auditTrail($request ,'Data with ID '.$id.' Has been Updated !');
}
return Redirect::to($return)->with('messagetext',\Lang::get('core.note_success'))->with('msgstatus','success');
} else {
return Redirect::to('adminorders/update/'.$request->input('SiparisID'))->with('messagetext',\Lang::get('core.note_error'))->with('msgstatus','error')
->withErrors($validator)->withInput();
}
}
public function postDelete( Request $request)
{
if($this->access['is_remove'] ==0)
return Redirect::to('dashboard')
->with('messagetext', \Lang::get('core.note_restric'))->with('msgstatus','error');
// delete multipe rows
if(count($request->input('ids')) >=1)
{
$this->model->destroy($request->input('ids'));
\DB::table('tb_orderdetail')->whereIn('SiparisID',$request->input('ids'))->delete();
\SiteHelpers::auditTrail( $request , "ID : ".implode(",",$request->input('ids'))." , Has Been Removed Successfull");
// redirect
return Redirect::to('adminorders?return='.self::returnUrl())
->with('messagetext', \Lang::get('core.note_success_delete'))->with('msgstatus','success');
} else {
return Redirect::to('adminorders?return='.self::returnUrl())
->with('messagetext','No Item Deleted')->with('msgstatus','error');
}
}
public static function display( )
{
$mode = isset($_GET['view']) ? 'view' : 'default' ;
$model = new Adminorders();
$info = $model::makeInfo('adminorders');
$data = array(
'pageTitle' => $info['title'],
'pageNote' => $info['note']
);
if($mode == 'view')
{
$id = $_GET['view'];
$row = $model::getRow($id);
if($row)
{
$data['row'] = $row;
$data['fields'] = \SiteHelpers::fieldLang($info['config']['grid']);
$data['id'] = $id;
return view('adminorders.public.view',$data);
}
} else {
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$params = array(
'page' => $page ,
'limit' => (isset($_GET['rows']) ? filter_var($_GET['rows'],FILTER_VALIDATE_INT) : 10 ) ,
'sort' => 'SiparisID' ,
'order' => 'asc',
'params' => '',
'global' => 1
);
$result = $model::getRows( $params );
$data['tableGrid'] = $info['config']['grid'];
$data['rowData'] = $result['rows'];
$page = $page >= 1 && filter_var($page, FILTER_VALIDATE_INT) !== false ? $page : 1;
$pagination = new Paginator($result['rows'], $result['total'], $params['limit']);
$pagination->setPath('');
$data['i'] = ($page * $params['limit'])- $params['limit'];
$data['pagination'] = $pagination;
return view('adminorders.public.index',$data);
}
}
function postSavepublic( Request $request)
{
$rules = $this->validateForm();
$validator = Validator::make($request->all(), $rules);
if ($validator->passes()) {
$data = $this->validatePost('tb_orders');
$this->model->insertRow($data , $request->input('SiparisID'));
return Redirect::back()->with('messagetext','<p class="alert alert-success">'.\Lang::get('core.note_success').'</p>')->with('msgstatus','success');
} else {
return Redirect::back()->with('messagetext','<p class="alert alert-danger">'.\Lang::get('core.note_error').'</p>')->with('msgstatus','error')
->withErrors($validator)->withInput();
}
}
}

Get selected value from select_from_array field using laravel 5.2 Backpack

I am using Laravel 5.2 Backpack in my new project where I have a select_from_array field in my form, depending upon the selected value I want data to be displayed in another select_from_array field. Don't know how to do that. Please help me with this. This is my code
Controller.php
public function __construct()
{
if (Request::segment(3) == 'create') {
$parentField1 = [
'name' => 'cat_id',
'label' => 'Category',
'type' => 'select_from_array',
'options' => $this->categories(),
'allows_null' => false,
];
$parentField = [
'name' => 'subCat_id',
'label' => 'SubCategory',
'type' => 'select_from_array',
'options' => $this->subcategories(),
'allows_null' => false,
];
array_unshift($this->crud['fields'], $parentField1,$parentField);
}
public function categories()
{
$cat = Request::get('cat_id');
$currentId = 0;
if (Request::segment(4) == 'edit' and is_numeric(Request::segment(3))) {
$currentId = Request::segment(3);
}
$entries = Category::where('translation_lang', config('app.locale'))->where('parent_id',0)->orderBy('lft')->get();
if (is_null($entries)) {
return [];
}
$tab = [];
$tab[0] = 'Root';
foreach ($entries as $entry) {
if ($entry->id != $currentId) {
$tab[$entry->translation_of] = '- ' . $entry->name;
}
}
return $tab;
}
public function subcategories()
{
$currentId = 0;
if (Request::segment(4) == 'edit' and is_numeric(Request::segment(3))) {
$currentId = Request::segment(3);
}
$entries = Category::where('translation_lang', config('app.locale'))->where('parent_id','!=' ,0)->orderBy('lft')->get();
if (is_null($entries)) {
return [];
}
$tab = [];
$tab[0] = 'Root';
foreach ($entries as $entry) {
if ($entry->id != $currentId) {
$tab[$entry->translation_of] = '- ' . $entry->name;
}
}
return $tab;
}
I want the id of selected option in the subcategories() where I can use the id to get the data.
I think the best way for you is to create a custom field type for this particular purpose, that includes both selects. Follow this procedure. Start from the select2.blade.php file and add the javascript you need to achieve your goal (on change event on first select2, change the options in the next select2).

Categories