I have laravel controller like this:
public function postSessionTopic() {
$article_id = Input::get('article_id', 0);
$comment_id = Input::get('comment_id', 0);
\Session::set('page_topic_id', $article_id);
\Session::set('page_comment_id', $comment_id);
\\comment - I have tried \Session::put too, but that doesn't change anything
}
I use it, when user click on a article. I print_r out my session variable in this controller and everything looks fine. But after that I refresh my page, and there I read value from session, and sometimes it load old value or doesn't load anything. I can't understand why, because in controller i can see, that correct value is saved!
In my page, i get that value like this:
\Session::get('page_topic_id', 0)
Probably you do something wrong. You should make sure that in both cases you uses exactly same domain (with or without www).
In this controller when you don't have any input you set to session variables 0. This can also be an issue if you launch this method when you don't have any input.
You could try with adding this basic route:
Route::get('/session', function() {
$page_topic = Session::get('page_topic_id', 1);
$page_comment = Session::get('page_comment_id', 1);
echo $page_topic.' '.$page_comment.'<br />';
$article_id = $page_topic * 2;
$comment_id = $page_comment * 3;
Session::set('page_topic_id', $article_id);
Session::set('page_comment_id', $comment_id);
});
As you see it's working perfectly (but you need to remove session cookie before trying with this path).
You get
1 1
2 3
4 9
8 27
and so on. Everything as expected
Answer was - two ajax at one time. Don't do that, if you store something in session.
The session in Laravel doesn't consider changes permanent unless you generate a response (and that's the result of using symphony as it's base). So make sure your app->run() ends properly and returns a response before refreshing. Your problem is mostly caused by a die() method somewhere along your code or an unexpected exit of PHP instance/worker.
This is probably not your issue but if you are storing your laravel session in the database their is a limit on how large that value can be. The Laravel session migration has a field called "payload" that is a text type. If you exceed the limit on that field the entire session gets killed off. This was happening to me as I was dynamically adding json model data to my session.
Schema::create('sessions', function (Blueprint $table) {
$table->string('id')->unique();
$table->text('payload');
$table->integer('last_activity');
});
How much UTF-8 text fits in a MySQL "Text" field?
Related
I'm facing a weird problem which only happen in the production server (It's 100% normal in my local). I'm using Laravel 8, and have a model named Student. Inside the model, I created several scope methods like this:
public function scopeWhereAlreadySubmitData($query)
{
return $query->where('status_data_id', '!=', 1);
}
public function scopeWhereAlreadySubmitDocument($query)
{
return $query->where('status_document_id', '!=', 1);
}
Then I use the methods above in an AJAX controller to chain it with count method. Something like:
public function getAggregates()
{
$student = Student::with(['something', 'somethingElse']);
$count_student_already_submit_data = $student->whereAlreadySubmitData()->count();
$count_student_already_submit_document = $student->whereAlreadySubmitDocument()->count();
return compact('count_student_already_submit_data', 'count_student_already_submit_document');
}
Here's is where the weird thing happens: while the controller above produce the correct value in my local, in production count_student_already_submit_data has a correct value but count_student_already_submit_document has zero value. Seeing at the database directly, count_student_already_submit_document should have value more than zero as there are many records has status_document_id not equals to 1.
I've also tried to use the scopeWhereAlreadySubmitDocument method in tinker. Both in local and production, it shows the correct value, not just zero.
Another thing to note is that Student model actually had 4 scope methods like the above, not just 2. 3 of them is working correctly, and only 1 is not. Plus, there's another controller using all the scope methods above and all of them are showing the correct value.
Have you ever face such thing? What could be the problem behind this? Your input is appreciated.
Turns out this is because the query builder is effected by the given chain. The weird thing I mentioned about "local vs production" is likely doesn't gets noticed in the local because its only has a few records. I should've use clone() when chaining the builder. See the topic below for more information.
Laravel query builder - re-use query with amended where statement
I'm new to laravel. I found a way here how to count article views, I used it on my own and it works as it should
$viewed = Session::get('viewed_article', []);
if (!in_array($article->id, $viewed)) {
$article->increment('views');
Session::push('viewed_article', $article->id);
}
But the only thing I do not fully understand is how it works and what it does, which makes me feel a little uneasy.
Who is not difficult, can you explain how this function works?
The first line:
$viewed = Session::get('viewed_article', []);
uses the Session facade to get the data with the key viewed_article from the session, or if nothing exists for that key, set $viewed to an empty array instead (the second argument sets the default value).
The next line, the if statement:
if (!in_array($article->id, $viewed)) {
makes sure that the current article id is not in the $viewed array.
If this condition is true (i.e. the article is not in the array), then the views are incremented (i.e. increased by one) on the article:
$article->increment('views');
Lastly, the article id is added into the viewed_article session data, so the next time the code runs, it won't count the view again:
Session::push('viewed_article', $article->id);
I have a query which I use all over my routes.php under almost every get request and also use the results in many of my views. It makes more sense at this point for me to call the query once and be able to use it globally without ever having to call it again.
Here's the query:
$followers = Follower::where('user_id', '1')
->get();
How can I do this?
Why not just execute the query once in an init function and store the result into a global variable?
global $followers = Follower::where('user_id', '1')
->get();
you can store it to the session every time the user logs in
Like this exemple
$followers = Follower::where('user_id', '1')
->first();
Session::put('followers', 'value');
whenever you want that you can access it like this
$value = Session::get('followers');
The another answer with session is a simple solution but
I would suggest you to use Laravel Cache for this purpose (because this is the standard practice).
The Laravel Cache::remember accepts three parameters.
key: make an md5 key of 'followers' and 'user id'
time: time in minutes you want to cache the values (depending how frequently your values will be changed)
A closure function which runs when no value is found corresponding to the key. (this method will query once, in this case, and store the value in your cache)
Just do the following in your BaseController's constructor:
$id = 1; //User id
$key = md5('followers'.$id);
$minutes = 60; //cache for 1 hour, change it accordingly
$followers = Cache::remember($key, $minutes, function() use ($id) {
return Follower::where('user_id', $id)->get();
});
Now of course to use Cache you need to use some Cache driver like Redis.
If you don't have how to setup it Read my other answer.
Though it may be little longer solution for your problem, and may take you 15-20 min to set up and run everything, but believe me once you start using cache you will love it.
If I open a form to edit and without changing any value just hit Submit button to update, it updates the row in the table i.e. it changes the updated_at time and even executes some code in bootXXXX(static::saving(function($model) {}) function.
I do not want that to happen.
How can I find If user changed nothing and its a blank submit button hit?
Of course before update I can fetch the current values and compare them with input $request->all() and decide to update or not, but Is there any better way to do so the laravel way?
Thanks,
K
you have 2 methods one is getDirty() by using this you will get current changed input value, another one is getOriginal() if you use that you will get what previous data you have
By using those 2 methods i am giving here a example,may be it will help you
static::saving(function($model)
{
foreach($model->getDirty() as $attribute => $value){
$original= $model->getOriginal($attribute);
echo "Changed $attribute from '$original' to '$value'<br/>\r\n";
}
return true; //if false the model wont save!
});
can anyone give me an example on how to create Sessions and write data to it. I've seen syntax on how to write data to a session using write command. But how to create a session and retrieve the values in it.
In my application, I have two data, form_id and user_id that needs to be used in all the page requests. So how do I save it as a session variable and use it across the application?
EDIT
function register()
{
$userId=$this->User->registerUser($this->data);
$this->Session->write('User.UserId',$userId);
//echo "session".$this->Session->read('User.UserId');
$this->User->data=$this->data;
if (!$this->User->validates())
{
$this->Flash('Please enter valid inputs','/forms' );
return;
}
$this->Flash('User account created','/forms/homepage/'.$userId);
}
How to use the session variable 'User.UserId' instead of $userId in $this->Flash('User account created','/forms/homepage/'.$userId);
And can I use this variable in all my view files,because in all the page requests I also pass the userId?
EDIT 2
I have 2 controllers,user and form. I write the userid to a session variable in the users_controller. I have a view file called homepage.ctp,whose action is in the forms_controller. Now how can I use the session variable defined in the users_controller in the homepage? Sorry if I am asking silly questions. I went through the cakebook,but my doubts weren't cleared. I'm also trying trial and error method of coding,so please help me.
EDIT 3
I have a session variable 'uid' which is the user id in the home page action of a controller.
$this->Session->write('uid',$this->data['Form']['created_by']);
I need the same variable in the design action method of the same controller.
When I give
$uid=$this->Session->read('uid');
echo "uid: ".$uid;
the value is not echoed.
Can't I use the session variable in the same controller?
The bakery is your best friend:
http://book.cakephp.org/view/398/Methods
All your session read/writes belong in the controller:
$this->Session->write('Person.eyeColor', 'Green');
echo $this->Session->read('Person.eyeColor'); // Green
In cake php you can create session like this
$this->request->session()->write('user_id', 10);
and you can read session value like this
echo $this->request->session()->read('user_id');
Super Simple!
You don't have to write any code to create session, they are already built in. Then you just use the read and write sessions as mentioned above. Also see here for more details:
http://book.cakephp.org/2.0/en/core-libraries/components/sessions.html
Used in Controllers
http://book.cakephp.org/2.0/en/core-libraries/helpers/session.html
Used in Views
cakephp 4 example of session usage in controllers, views and cells
$session = $this->request->getSession();
$session->write('abc', 'apple');
echo $session->read('abc');
In this case it would be:
$this->Flash('User account created','/forms/homepage/'.$this->Session->read('User.UserId'));
and your second question is anwered by Jason Miy (http://api.cakephp.org/class/session-helper). You can simply use this in your view:
$userId = $session->read('User.UserId');
Reading the appropriate cookbook pages slowly and carefully usually helps a lot...
I found out the reason why the uid wasn't being echoed(edit 3 part of the question).
It is due to a silly mistake, had a white space after the end tag ?> in the controller. Now it is working fine.
when I have strange session behavior, and this help me.
MODEL:
function clearAllDBCache() {
$db =& ConnectionManager::getDataSource($this->useDbConfig);
$db->_queryCache = array();
}
`
Acess your Helper SessionHelper in lib/Cake/View/Helper/SessionHelper.php and add the method:
public function write($name = null) {
return CakeSession::write($name);
}