While working on a Laravel 4.2 app, I have recently noticed that calls to Session::flash (and similarly Input::flash) sometimes behave inconsistently.
One particular example: I want to flash some data from the edit function so that I can access it in the corresponding update function. The edit view contains a fairly simple form, including one field that is loaded via an AJAX call after the user selects an option from a drop-down. Here is my MCVE:
In MyController.php:
<?php
class MyController {
public function edit($id) {
Session::flash('somevar', "myvalue");
return View::make('edit');
}
public function update($id) {
var_dump(Session::all()); die();
if (Session::has('somevar')) {
// do stuff
}
return Redirect::to('/');
}
}
?>
In AjaxController.php:
<?php
class AjaxController {
public function getinfo() {
return "here's that data you wanted";
}
}
?>
In edit.blade.php:
<script type="text/javascript">
$('form select[name=foo]').change(function() {
$.ajax({
url: '/ajax/getinfo'
success: function(data) {
alert(data);
}
});
});
</script>
Update
Sometimes the session dump in update() will show the flash data, but sometimes it is missing.
What is going wrong?
The issue is the extra AJAX call to populate one of the fields. Since this counts as a request, the flash data is active for that request, but not the next one.
To fix this issue, I added Session::reflash() to the first line of the function triggered by the AJAX call, like so:
<?php
class AjaxController {
public function getinfo() {
Session::reflash();
return "here's that data you wanted";
}
}
?>
Related
In my code, I created a trait to clear out some cache. It's code looks like below.
<?php
namespace App\Models\Traits;
use App\Classes\Utilities\ResponseCache as ResponseCache;
trait ClearsResponseCache {
public static function bootClearsResponseCache() {
static::saving(function () {
ResponseCache::removeAll();
});
static::updating(function () {
ResponseCache::removeAll();
});
static::deleting(function () {
ResponseCache::removeAll();
});
}
}
In my controller I have a custom query to select some rows from the database.
public function fetchAllItems() {
$items = DB::select('My custom query');
return response()->json($items);
}
Now, when this function is run, the saving event of ClearsResponseCache is fired, leading to my cache being deleted. Any idea why that event is being fired?
I have a Controller and a few functions inside. Some function are basically save data into DB. One of the function require a filter that specific type of user can't do write access into DB.
My question is how do I block to save data into db for specific user role.
class TestController extends AppController {
public function beforeFilter(){
if(in_array($this->action, ['f1','f2'])) {
if($this->authenticatedUser['role'] == 'readonly') {
//return message
//block save data into db
}
}
}
public function f1() {
//save data into db
}
public function f2() {
//save data into db
}
public function f3() {
}
}
When I tried to write using f1 or f2, it goes to beforeFilter and show the message as well but data save into db also. How should I block it while I tried to write data into db on beforeFilter.
Here is some logic:
check if the request is a post
check which method is requested
if both checks match, create a flash message and make a GET redirect to the desired method
if($this->request->is('post') && in_array($this->action, ['f1','f2'])) {
if($this->authenticatedUser['role'] == 'readonly') {
//set flash message
//get redirect to action
}
}
Next
function f1() {
// if request is post, save data
// else return find data or empty object / array
}
Im pretty new to this framework. The issue is that form validation callbacks are not being called inside a model. It will work inside a controller without an issue.
Am I right thinking logic/database stuff is to be inside a model rather than controller? What am I doing wrong? Im trying to do this as best as possible.
Example Model Method:
//The Callback
function check_delete()
{
$this->form_validation->set_message('check_address', 'This is a test message');
return false;
}
function test()
{
//The Check
$this->form_validation->set_rules('address_id', 'ID', 'required|callback_check_delete');
//On Success
if($this->form_validation->Run() == TRUE) {
//Do something interesting on success!
}
}
I have an html with a script that is like so (btw, HAVe to use old fashioned post in my html for reasons)...
#extends('layout')
// ... includes for jquery and ajax
<script>
var theVariableINeedInLaravel = "SomeInterestingStringI'mSure"; // in reality, this is a stringify.
$.post ("foo", function(theVariableINeedInLaravel) {
}
</script>
#stop
Then in routes.php...
<?php
Route::post('foo', 'ThatOneController#getValue');
?>
Then, in the related controller....
ThatOneController.php
class ThatOneController extends \BaseController{
public function getValue(){
error_log(print_r($_POST,true)); // returns nothing.
error_log(print_r(input::all()); // returns nothing.
}
}
Or, an alternate version of the function...
public function getValue(Request $request){
error_log(print_r($request->all()); // returns nothing.
}
None of them seem to work. How can I get my post variable?
try this
use Request;
class ThatOneController extends \BaseController{
public function getValue(){
print_r(Request::all());
}
Turns out that even if $_post isn't always accessible from inside a controller function, it is directly accessible from Routes. It's a bit hacky, and "not the laravel way" but you can use $_post in routes to get and pass into other variables to get back into the normal flow.
In my template I call a function like this:
loadResults('asc');
function loadResults(order) {
return $.get('{{ url('_example_results', { 'order' : ''}) }}'+order, function (html) {
$('#results').html(html);
});
}
The function in my controller looks like this:
public function resultsAction($order, Request $request)
{
// content is not crucial for solving my problem
}
My results don't get loaded, I get the following error:
Controller "...resultsAction()" requires that you provide a value for the "$order" argument (because there is no default value or because there is a non optional argument after this one).
What adjustments do I need to make?
Because TWIG render the page BEFORE you can act with js, you can't compose the right route with TWIG.
You can archive your problem with two approach:
1) Make the param optional and pass it on query string as follow:
js
loadResults('asc');
function loadResults(order) {
return $.get('{{ url('_example_results') }}'+"?order="order, function (html) {
$('#results').html(html);
});
}
controller
public function resultsAction(Request $request)
{
//...
$order= $request->get('order','asc'); // second parameter is the default if is null
}
2) Using FOSJsRoutingBundle
Hope this help