I'm having problems creating a cookie with laravel, the thing is that sometimes the value of this cookie changes into a null intead of its real value which makes my system give errors that I've programed to show in case this cookie dont exist.
This happens when a reaload the page, I've debugged with dd() and every time that I reload the page the value changes from'activo' to 'null' and from 'null' to 'activo', why does this happen?
My code:
public function store_inicio(Request $request)
{
$empresa_id = $request->input('empresa_id');
$empresa = Empresa::find($empresa_id);
$cierre = $empresa->inicio_caja()->orderBy('id', 'desc')->first();
if (isset($cierre)) {
if (!isset($cierre->cierre)) {
Cookie::queue('estado_caja', 'activo', 180);
Cookie::queue('numero_caja', $cierre->caja, 180);
} else {
$this->crear_inicio($request, $empresa);
}
} else {
$this->crear_inicio($request, $empresa);
}
return redirect('ventas');
}
private function crear_inicio($request, $empresa)
{
$aux_usuario = $request->input('usuario_inicio_caja');
$usuario = User::where('name', $aux_usuario)->first();
$numero_caja = $request->input('caja_inicio_caja');
$valor = $request->input('valor_inicio_caja');
$inicio_caja = new Inicio_caja();
$inicio_caja->user_id = $usuario->id;
$inicio_caja->caja = $numero_caja;
$inicio_caja->valor = $valor;
$inicio_caja->save();
$empresa->inicio_caja()->syncWithoutDetaching($inicio_caja->id);
Cookie::queue('estado_caja', 'activo', 600);
Cookie::queue('numero_caja', $numero_caja, 600);
}
Related
after I inserting data, what shows on the column table "Jumlah Hasil Perah" shows '0'. but after refreshing the browser, the value shows up the result.
here's the code
Model (m_hasilperah):
public function jumlahPerahSapi($id)
{
$this->db->select('hasilPerahPagi, hasilPerahSore');
$this->db->where('idSapi', $id);
$cek = $this->db->get('tb_hasilperah');
if ($cek) {
$this->db->set('jumlahPerah', "hasilPerahPagi + hasilPerahSore", FALSE);
$this->db->where('idSapi', $id);
$this->db->update('tb_hasilperah');
}
return false;
}
Controller
public function tambahHasilPerah(){
$idSapi = $this->input->post('idSapi');
$tglPerah = $this->input->post('tglPerah');
$hasilPerahPagi = $this->input->post('hasilPerahPagi');
$hasilPerahSore = $this->input->post('hasilPerahSore');
$jumlahPerah = $this->m_hasilperah->jumlahPerahSapi($idSapi);;
$data =
[
'idSapi' => $idSapi,
'tglPerah' => $tglPerah,
'hasilPerahPagi' => $hasilPerahPagi,
'hasilPerahSore' => $hasilPerahSore,
'jumlahPerah' => $jumlahPerah
];
$insert = $this->m_hasilperah->tambahHasilPerahModel($data, $idSapi);
if ($insert) {
redirect('C_hasilperah/tampilHasilPerah/' . $idSapi, 'refresh');
} else {
echo 'gagal';
}
}
Screenshot:
View after insert(before manual refresh)
View after manual refresh
Your Model method jumlahPerahSapi() every time returned false. Even if after the data update. Please look into this.
Your Model function jumlahPerahSapi($id) is always return false even inserted successfully in DB.
So This is not run redirect('C_hasilperah/tampilHasilPerah/' . $idSapi, 'refresh');
Every time run echo 'gagal';
Modify the model function as follows.
public function jumlahPerahSapi($id)
{
$this->db->select('hasilPerahPagi, hasilPerahSore');
$this->db->where('idSapi', $id);
$cek = $this->db->get('tb_hasilperah');
if ($cek) {
$this->db->set('jumlahPerah', "hasilPerahPagi + hasilPerahSore", FALSE);
$this->db->where('idSapi', $id);
$this->db->update('tb_hasilperah');
return true;
}
return false;
}
I'm trying to understand the reason of this error message from postman when test API.
When I am testing my REST API from postman, it gives me error
ErrorException (E_NOTICE)
Trying to get property 'staff' of non-object
I try to find the problem but i can't find it. I kept searching for this but couldn't find an answer that will make this clear.
Anyone can help me on this?
Thanks!
This my code snippet
public function updatestatus($request, $leave, $is_api=0)
{
$status = $request->get('status');
$user = $is_api? JWTAuth::parseToken()->authenticate():Auth::user();
// $user = Auth::user();
$staff= $user->ref_user;
$applying_staff = $leave->staff;
$applying_user = $applying_staff->main_user;
//Approved
if($status==2 && $leave->status==1)
{
$leave->status =2;
$leave->approved_by_staff_id = $staff->staff_id;
$leave->approved_date = new Carbon('today');
$leave->save();
if($user->centre_id)
Helper::ClearObjective(10,$user->centre_id);
dispatch(new EmailJob($applying_user->email,new LeaveNotification(route('staff.leave.show',$leave->id), $leave->statusStr)))
->onConnection('database')
->onQueue('emails');
return response()->json(['Success'=>'Success']);
//send email
}
// Rejected
else if($status==3 && $leave->status==1)
{
$leave->status =3;
$leave->status_rejected_reason = $request->get('reason',null);
$leave->save();
if($user->centre_id)
Helper::ClearObjective(10,$user->centre_id);
$leave_cat = LeaveCategory::find($leave->leave_type);
if($leave_cat->leave_status!=0)
{
$leave_ent = $applying_staff->leaves()->where('leave_type',$leave->leave_type)->first();
if($leave_ent)
{
$leave_ent->leave_remaining += $leave->leave_days;
$leave_ent->save();
}
}
dispatch(new EmailJob($applying_user->email,new LeaveNotification(route('staff.leave.show',$leave->id), $leave->statusStr, $leave->status_rejected_reason)))
->onConnection('database')
->onQueue('emails');
//send email
}
//Cancelled
else if(($status==4 && $leave->status==2) || ($status==4 && $leave->staff_id == $staff->staff_id))
{
$leave->status =4;
$leave->status_rejected_reason = $request->get('reason',null);
$leave->save();
$leave_cat = LeaveCategory::find($leave->leave_type);
if($leave_cat->leave_status!=0)
{
$leave_ent = $applying_staff->leaves()->where('leave_type',$leave->leave_type)->first();
if($leave_ent)
{
$leave_ent->leave_remaining += $leave->leave_days;
$leave_ent->save();
}
}
dispatch(new EmailJob($applying_user->email,new LeaveNotification(route('staff.leave.show',$leave->id), $leave->statusStr,$leave->status_rejected_reason)))
->onConnection('database')
->onQueue('emails');
//send email
}
// return reponse()->toJson(compact('leave'));
return $leave;
}
Calling API
public function update(Request $request)
{
return $this->leaveApplicationRepository->updatestatus($request,1);
}
your updatestatus() need 3 parameter and your update() function pass only 2 paramenter;
public function update(Request $request)
{
// please provide you leave data
$leave = "your data is here";
return $this->leaveApplicationRepository->updatestatus($request,$leave, 1);
}
From the context that I can see, it is trying to reference the staff variable in:
$applying_staff = $leave->staff;
The non-object message will mean that $leave itself is the problem. Since you are passing in 1 to the call:
return $this->leaveApplicationRepository->updatestatus($request,1);
the 1 becomes the $leave parameter, and that is not an object, hence the error.
Maybe you think that by passing in 1, it will find the correct model automatically? This is not the case. You need to load that model explicitly.
i am creating a website which needs to store user info and save to cookie.
here is my get cookie controller
public function index($id, Request $request)
{
$petitions = Petitions::where('id',$id)->first();
$sign->name = $request->cookie('name');
$sign->email = $request->cookie('email');
return view('petitions.index', compact('petitions'))->with(['name'=>$sign->name,'email'=>$sign->email]);
}
and here is set cookie controller
public function store(Request $request)
{
$sign = new ActionUsers();
$sign->name = $request->get('name');
$sign->email = $request->get('email');
$sign->job = $request->get('job');
$sign->reason = $request->get('reason');
$sign->ip_address = $request->get('ip_address');
$sign->petition_id = $request->get('petition_id');
$sign->is_anonymous = $request->get('is_anonymous');
$sign->save();
$name_cookie = cookie('name', $sign->name, 30);
$email_cookie = cookie('email', $sign->email, 30);
return back()->withCookie($name_cookie,$email_cookie);
}
my view to check cookie existed
#if( isset($sign->name) && isset($sign->email) )
done!
#else Oops! Error
and return error Creating default object from empty value in $sign->name = $request->cookie('name');
$sign->email = $request->cookie('email');
anyone help me solve that! thank you
Try return in store function as :
return back()->withCookie($name_cookie)->withCookie($email_cookie);
There are several ways to do this:
$response = new \Illuminate\Http\Response(view('your_view'));
$response->withCookie(cookie('cookieName' , 'cookieValue' , expires_in_minutes));
return $response;
or
\Cookie::queue('cookieName', 'cookieValue', expires_in_minutes);
return view('your_view');
you can also use this code to get cookies :
$request->cookie('coockieName');
I'm creating my own custom SessionHandler to store my session information in a postgresql 9.3 database and I'm having a problem where the session data passed to the write() method isn't being written to the database, but the session name is??
Things that I know for a fact
My custom class is handling the sessions when session_start() is called - as tested with echoing output from the various methods and no session files are being created in /tmp
The $session_data arg in write() contains the proper serialized string as shown by echoing the contents in the write() method.
$session_name is being written to the database just fine and so is a BLANK serialized string a:0:{}.
Things I'm confused about:
Echoing the contents of $_SESSION['test_var1'] shows the correct value stored, even if read() is empty or returning no value??
If the session name is saved in the DB just fine, why isn't the session data?
Server Configuration
OS: Gentoo
Database: Postgresql 9.3
Web Server: NGINX 1.7.6
PHP 5.5.18 connected to NGINX via FPM
PHP ini session settings
session.save_handler = user
session.use_strict_mode = 1
session.use_cookies = 1
session.cookie_secure = 1
session.use_only_cookies = 1
session.name = _g
session.auto_start = 0
session.serialize_handler = php_serialize
class SessionManagement implements SessionHandlerInterface {
private $_id = '';
private $_link = null;
public function __construct() {
session_set_save_handler(
[$this, 'open'],
[$this, 'close'],
[$this, 'read'],
[$this, 'write'],
[$this, 'destroy'],
[$this, 'gc']
);
}
public function open($save_path, $session_id) {
echo 'open called<br/>';
$this->_id = $session_id;
$this->_link = new PDO('pgsql:host=' . $_SERVER['DB_HOST'] . ';dbname=' . $_SERVER['DB_DB'],
$_SERVER['DB_USER'],
$_SERVER['DB_PASS']);
}
public function close() {
echo 'close called<br/>';
}
public function destroy($session_id) {
echo 'destroying '.$session_id, '<br/>';
}
public function gc($maxlifetime) {
echo 'GC called<br/>';
}
public function read($session_name) {
$name = $this->_id.'_'.$session_name;
$sql = 'SELECT session_data FROM sessions WHERE session_name = :name';
if ($rel = $this->_link->prepare($sql)) {
if ($rel->execute([':name' => $name])) {
return $rel->fetch(PDO::FETCH_ASSOC)['session_data'];
} else {
return false;
}
} else {
return false;
}
return '';
}
public function write($session_name, $session_data) {
echo 'Session data: '.$session_data.'<br/>';
$name = $this->_id . '_' . $session_name;
$data = $session_data;
$sql = "SELECT 1 FROM sessions WHERE session_name = :name";
if ($rel = $this->_link->prepare($sql)) {
if ($rel->execute([':name' => $name])) {
if ($rel->rowCount()) {
echo 'Updating...<br/>';
$sql = 'UPDATE sessions SET session_data = :data WHERE session_name = :name';
if ($rel = $this->_link->prepare($sql)) {
if ($rel->execute([':name' => $name, ':data' => $data])) {
echo 'Update success...<br/>';
} else {
echo 'Update failed...<br/>';
var_dump($rel->errorInfo());
}
}
} else {
echo 'Inserting...<br/>';
$sql = 'INSERT INTO sessions (session_name, session_data) ';
$sql .= 'VALUES(:name, :data)';
if ($rel = $this->_link->prepare($sql)) {
if ($rel->execute([':name' => $name, ':data' => $data])) {
echo 'Insert success...<br/>';
} else {
echo 'Insert failed...<br/>';
var_dump($rel->errorInfo());
}
}
}
}
}
}
}
Test code:
new SessionManagement();
session_start();
$_SESSION['test_var1'] = 'some test data';
session_write_close(); // Making sure writing is finished
echo $_SESSION['test_var1'];
Output via test page
open called
Session data: a:1:{s:9:"test_var1";s:14:"some test data";}
Inserting...
Insert success...
close called
some test data
Relevant database fields
session_name: _g_h8m64bsb7a72dpj56vgojn6f4k3ncdf97leihcqfupg2qtvpbo20
session_data: a:0:{}
I'm not sure if this is a database issue or a PHP issue. I've been messing with this for a few days now and decided it was time to ask the community. Hopefully someone has some insight as to what the problem is.
I think you must initialize PDO object outside of the Open function handler and the class itself
try to access to your PDO Object with a Global value or through a static variable.
This is my implementation with MYSQL for my project :
class Core_DB_SessionHandler implements SessionHandlerInterface
{
protected $options = array(); // Options de la session
protected static $db = NULL; // Acceder a la BDD
public function __construct($options, $pdo) {
$this->options = $options;
self::$db = $pdo;
}
public function open($savePath, $sessionName) {
$now = time();
$req = self::$db->prepare("DELETE FROM tbl_sessions WHERE expire < '{1}' ");
$req->execute(array($now));
return TRUE;
}
public function close() {
$this->gc(ini_get('session.gc_maxlifetime'));
}
public function read($id) {
$now = time();
$stmt = self::$db->query("SELECT data FROM tbl_sessions WHERE sid = '$id AND expire < '$now'");
$result = $stmt->fetchColumn();
return $result;
}
public function write($id, $data) {
if (array_key_exists('TIMEOUT', $_SESSION)) {
$newExp = $_SESSION['TIMEOUT'];
}
else {
$newExp = time() + $this->options['time_limiter'];
}
try {
$req = self::$db->prepare('INSERT INTO tbl_sessions (sid, data, expire) VALUES (:sid, :data, :expire)
ON DUPLICATE KEY UPDATE data = :data, expire = :expire');
$vals = array('sid' => $id, 'data' => $data, 'expire' => $newExp);
$req->execute($vals);
return TRUE;
}
catch (PDOException $e) {
throw new Core_Exception(sprintf('PDOException was thrown when trying to write the session data: %s', $e->getMessage()), 0, $e);
}
}
public function destroy($id) {
$stmt = self::$db->prepare("DELETE FROM tbl_sessions WHERE sid = '{1}'");
$stmt->execute(array($id));
//return ($stmt->rowCount() === 1) ? true : false;
return TRUE;
}
public function gc($maxlifetime) {
$now = time();
$req = self::$db->prepare("DELETE FROM tbl_sessions WHERE expire < '{1}' ");
$req->execute(array($now));
return TRUE;
}
}
and i initialize handler like this :
$handler = new Core_DB_SessionHandler($MyOptions, $MyPDO);
if (PHP5) {
if (!session_set_save_handler($handler, TRUE)) {
throw new Core_Exception('Erreur lors de l\'init des sessions !');
}
}
nb : In your Table structure don't use autoincrement for ID
Well, I've solved my problem, but it's hard to say if this fix was actually the problem in the first place.
In the read method, I changed the follow:
return $rel->fetch(PDO::FETCH_ASSOC)['session_data'];
to
$data $rel->fetch(PDO::FETCH_ASSOC)['session_data'];
return $data;
After this the session was writing $session_data to the database without any problem. That's all well and dandy, but it doesn't explain why it didn't work in the first place. I mainly say this because upon switching the statement back everything continued to work. As in, I can't reproduce the issue now. So it's hard for me to even say that this was the problem in the first place.
Hopefully this helps someone. I've been unable to find more information about it, but it something does show up I'll be sure to add it here.
I kind of understand what is needed but I am new to ZF2 so just need pushing in the right direction.
I currently have a route set up, for example, viewsystem/1, which has the form [action][id].
When a person clicks on a link, they change their id, for example, viewsystem/5.
In the model where I run the SQL, I wish the id to change for the SQL statement:
->where('system.Id = "'.$id.'" ')
Can anyone explain where I can "get" the parameter and use this as a variable in the SQL?
Do I need to do something in the controller? Can I not just use a $_GET or something?
I have updated this, as it is quite clear to see what is happening. The route for viewsystemAction() is different to the route of ajaxviewsystemAction().
When I use $id = (int) $this->params()->fromRoute('id', 0); inside the viewsystemAction(), it echoes back the page link id route, for example viewsystem/220
When I use $id = (int) $this->params()->fromRoute('id', 0); inside the ajaxviewsystemAction(), it echoes back the 0 as the route id.
I need the route to be passed through this function
private function getSourceViewAllSystems($id)
{
return $this->getSystemsTable()->fetchViewAllSystems($id);
}
public function viewsystemAction()
{
$id = (int) $this->params()->fromRoute('id', 0);
echo $id; //i see the correct id for example 220 from the route in the browser
}
public function ajaxviewsystemAction()
{
$id = (int) $this->params()->fromRoute('id', 0);
echo $id; //to see the id of the route with the ajax page
//displays 0 and not the route id from the viewsystemAction
$table = new TableExample\Advance();
$table->setAdapter($this->getDbAdapter())
->setSource($this->getSourceViewAllSystems($id))
->setParamAdapter($this->getRequest()->getPost());
return $this->htmlResponse($table->render('custom' , 'custom-b2'));
}
To try explain a bit better here is my issue.
As you can see i am passing a param as you suggested into fetchViewAllSystems($id = 1);
fetchViewAllSystems is in my model and works perfectly, with the 1 there, it displays the system1.
however, the 1 needs to be the url id.
$id = (int) $this->params()->fromRoute('id', 0);
This gets the ID in the viewaction, but viewaction does not control the fetchViewAllSystems so it is quite tricky to pass this value from the url.
private function getSourceViewAllSystems()
{
return $this->getSystemsTable()->fetchViewAllSystems($id = 1);
}
public function viewsystemAction()
{
$id = (int) $this->params()->fromRoute('id', 0);
/*if (!$id) {
return $this->redirect()->toRoute('systems', array(
'action' => 'activesystems'
));
}*/
echo $id;
}
public function ajaxviewsystemAction()
{
/*$table = new TableExample\Base();
$table->setAdapter($this->getDbAdapter())
->setSource($this->getSourceViewAllSystems())
->setParamAdapter($this->getRequest()->getPost())
;
return $this->htmlResponse($table->render());*/
$table = new TableExample\Advance();
$table->setAdapter($this->getDbAdapter())
->setSource($this->getSourceViewAllSystems())
->setParamAdapter($this->getRequest()->getPost())
;
return $this->htmlResponse($table->render('custom' , 'custom-b2'));
echo $id;
}
To get a $_GET params in your controller, do like this:
// your IndexController.php
public function indexAction(){
$viewmodel = new ViewModel();
// get the ID
$id = $this->params('id', null); // null is my default value
// ...
return $viewmodel;
}
I highly recommend you to check this great example : https://github.com/akrabat/zf2-tutorial - http://zf2.readthedocs.org/en/latest/ref/overview.html
Check this line https://github.com/akrabat/zf2-tutorial/blob/master/module/Album/src/Album/Controller/AlbumController.php#L43
Get params
$id = $this->params('id', null); // null is my default value
or
$id = $request->query()->get('foo', 'default value');
Ref: http://zend-framework-community.634137.n4.nabble.com/ZF2-How-to-set-get-params-in-url-td4076050.html
controller.php
I don't know what getSystemsTable() returns and also fetchViewAllSystems but it should be like this
private function getSourceViewAllSystems($id = 1)
{
return $this->getSystemsTable()->fetchViewAllSystems($id);
}
public function viewsystemAction()
{
$id = $this->params()->fromRoute('id', null);
if (!$id) {
return $this->redirect()->toRoute('systems', array(
'action' => 'activesystems'
));
}
echo $id;
}
public function ajaxviewsystemAction()
{
$id = $this->params()->fromRoute('id', null);
$id = $this->params()->fromQuery()['id']; // if from ajax GET param
$table = new TableExample\Advance();
$table->setAdapter($this->getDbAdapter())
->setSource($this->getSourceViewAllSystems($id)) // send the current id
->setParamAdapter($this->getRequest()->getPost())
;
return $this->htmlResponse($table->render('custom' , 'custom-b2'));
}