Laravel 5.5 How to read flash data in a view page - laravel

My Controller is redirecting to this View with flash data(data from a table row). How do I print for example, just the "titulo" or "resumo"?
Or, instead of sending all the information from a table row to a single variable, do I have to send separately into different variables?
Thanks in advance.

This is the way you can send flash data from the backend:
public function show (){
//some code here
return redirect('/')->with('flash', 'message here');
}
and in the view you can display it like this:
{{session('flash')}}
The above will display "message here".
If you have return redirect('/')->with('alert', 'something happened');
{{session('alert')}}
The above will display "something happened".

Related

Best strategy to avoid Ajax roundtrips when updating databases in Laravel

Let's say I have a table with data in the rows coming from a database. On each row of this table there are helper buttons. These buttons perform instant operations on the database, such as setting a status code (for example sold, blocked, in progress), changing an invoice date for the row (for example from 18/11/2022 to null) and so on..
What I would like is that when a user clicks on one of these buttons, an ajax function will performs a request to the related controller that will show a modal box asking for confirmation (not a JS alert but HTML code that comes from a blade component).
So, giving a basic example in the case of the change of status code for the row, what I would do is first set up a route of this type:
Route::post('/status', [TableController::class, 'status']);
after that i will build my controller(using the related model Table) in a way that if the action value coming from the ajax request is confirm(the one coming from the confirmation modal), I will continue with the data update, if instead the action is something different such as status(the one coming from the helper button), then I will bring up my confirmation modal
class TableController extends Controller {
// Change status
public function status(Request $request){
if( $request['action'] == 'confirm' ) {
// Update DB
Table::where('id', $request->id)->update(['status' => 822]);
} else {
$id = $request->id;
// Show confirmation modal
return \Blade::render('<x-confirm :title="$title" :action="$action" :id="$id" />',
[
"title" => "Vuoi bloccare le seguenti disponibilità? ".$id ?,
"action" => "status",
"id" => $id
]);
}
}
If you notice the return of component part here
// Show confirmation modal
return \Blade::render('<x-confirm :title="$title" :action="$action" :id="$id" />'
I'm passing to the component the id of the row, and the action to perform, those datas will be usefull for the next ajax request coming from the confirmation modal, that will update the row in the database. But basically what is happening here?
Send data from frontend to the controller(id of the row, status action, status code).
Send back the same data from the backend to modal component to fill the ajax confirmation request.
Resend back to the server the same data to catch the confirm statement and update the database.
This kind of approach always worked for me, but when things becomes complex(let's say that I have different kind of helpers like I said before, in example remove a date, change the owner, set some flags etc) this will become a mess, because I have everytime to send back the same data that I just received.
So my question:
Is there a way to avoid this thing to sending back and forward those datas? like something in the middle that stores what am I doing in the current session and can inform the modal box without this round trip? Also i am really thinking that my approach is completely wrong and out of mind, so i have to see things from a different point of view? This is because I am self-taught so I certainly have some gaps that I would like to fill.

show success message on same page after adding recording without reloadin the site in cakephp 2.x

I want to add a show sucess message using :-
session->flash(); ?> in view and added the message in controller :-
Session->setFlash("Record has been saved successfully."); ?>
But I donot want to reload the whole page.
I am just inserting the new record using ajax.. and refreshing the div having list of all record.
session->flash(); ?> this works if i reload the whole page.
how can I show message once the record is saved using ajax.
Solutions (i recommend the first one):
Create AJAX method in controller that return 200 code with JSON/HTML record's data or any other error code if sth goes wrong. Then in js do:
$.ajax({ ... }).done(function( data ) {
// Success, show the record and message
$('#flash').text('Success!').show();
// ...
}).error( function() {
// Error
$('#flash').text('Error!').show();
});
Refresh the records list by calling ajax method and return not only the view with list of all records, but also a flash message (in the same view). Then show it or move using javascript.

How to repopulate form after form validation and also keep the URI?

I have a problem repopulating my form after validation fails. Problem is my url contains an additional uri which I access by clicking a link. This is what it looks like:
http://www.example.com/admin/trivia/add/5
At first trouble was that the segment 4 of the uri completely disappeared, so even though the validation errors showed and the form was repopulated, I lost my added uri.
Then I found in another question that the solution was to set form open like this:
echo form_open(current_url());
Problem is now it isn't showing any validation errors and the form is not repopulated. Is there a way to achieve this?
This is what my controller looks like:
function add()
{
$data = array('id' => $this->uri->segment(4));
if($_POST)
{
$this->_processForm();
}
$this->load->view('admin/trivia_form', $data);
}
And inside _processForm() I got all the validation rules, error message and redirecting in case success.
[edit] Here is my _processForm() :
function _processForm()
{
$this->load->library('form_validation');
//validation rules go here
//validation error messages
$this->form_validation->set_rules($rules);
$this->form_validation->set_error_delimiters('<div style="color:red">', '</div>');
if ($this->form_validation->run())
{
//get input from form and assign it to array
//save data in DB with model
if($this->madmin->save_trivia($fields))
{
//if save is correct, then redirect
}
else
{
//if not show errors, no redirecting.
}
}//end if validation
}
To keep the same url, you can do all things in a same controller function.
In your controller
function add($id)
{
if($this->input->server('REQUEST_METHOD') === 'POST')// form submitted
{
// do form action code
// redirect if success
}
// do your actual stuff to load. you may get validation error in view file as usual if validation failed
}
to repopulate the form fields you are going to need to reset the field values when submitting it as exampled here and to meke it open the same page you can use redirect() function as bellow:
redirect('trivia/add/5','refresh');
i don't know what you are trying to do, but try this to repopulate the form with the values user entered
<?php
echo form_input('myfield',set_value('myfield'),'placeholder="xyz"');
?>

Using browser back button in triggers flash message in CakePHP again

I just came across a bit of a puzzling situation. My controller action looks like this:
public function myaction($eventId = false) {
if(!$eventId) {
//list all events
$data = foo;
} else {
if(!$this->Event->findById($eventId) )
{
$this->Session->setFlash('myerror message', 'flash_frontend_message');
$this->redirect(array('controller' => 'events', 'action' => 'myaction'));
} else {
// display event information
$data = foo;
}
}
$this->set($data);
}
If I call the function with an $eventId that is not found in the database, it outputs an error message and the user gets redirected back to the list of all events. However lets say I then select an eventId which is valid, view the relevant information and then press the browser back button, the previous flash message gets out put again, even though the URL in this case does not contain the $eventId.
I suppose what happens is that the page gets loaded from the browser cache rather then reloaded. I have tried to avoid storing the view in the cache like this:
<!--nocache-->
<?php echo $this->Session->flash(); ?>
<?php echo $this->Session->flash('auth'); ?>
<!--/nocache-->
but still, the flash message gets displayed.
Any idea how to prevent this behavior?
Is there perhaps a way to clear the flash after it has been displayed?
you are talking about the right cache but trying to fix it with the wrong cache.
<!--nocache-->
is php/html no cache statements in the file itself. it has nothing to do with the browser cache.
what you need to be doing is setting the right headers.
there is a convinience method in the request object for this exact thing:
http://book.cakephp.org/2.0/en/controllers/request-response.html#interacting-with-browser-caching
I use it in all my normal frontend actions via AppController:
public function beforeRender() {
$this->response->disableCache();
...
}

codeigniter : using flash data but no new page load?

Usually, I just set a $feedback var or array and then check for that to display in my views.
However, it occurred to me I should perhaps use flashdata instead.
The problem is sometimes - for say an edit record form, I may simply want to reload the form and display feedback - not redirect. when i use flashdata, it shows but then it shows on the next request as well.
What would be the best practice to use here?
CodeIgniter supports "flashdata", or session data that will only be available for the next server request, and are then automatically cleared.
u use hidden field for that
I would use the validation errors from the Form validation class and load those directly to the view in its 2nd argument.
$this->form_validation->set_error_delimiters('<p>', '</p>');
$content_data = array();
if (!$this->form_validation->run()) {
$content_data['errors'] = validation_errors();
}
$this->load->view('output_page', $content_data);
Then check in your view whether $errors isset.
Controller:
$data['message'] = 'some message you want to see on the form';
$this->load->view('yourView', $data);
View:
if (isset ($message)) : echo $message; endif;
...

Resources