C
C
ChertyakaNUB2020-10-28 18:41:07
Laravel
ChertyakaNUB, 2020-10-28 18:41:07

How to get each time new data in the template through the controller?

Hello!

There is a controller in which the code is written to get a list of files from a folder:

$path = public_path('images');
$files = File::files($path);
return view('show', ['files' => $files]);

There is a template in which we get a list:
@foreach($files as $file)
...
@endforeach


The question is, how can you call the $files variable with updated data to get the latest data, if we just added a file to a folder without reloading the page?

Well, for example, there is a button in the template that adds a file to a folder, how can I immediately update the data after adding it?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
C
ChertyakaNUB, 2020-10-28
@ChertyakaNUB

In general, I did this: I
removed the files variable from the view and moved all the code to a separate function and made an additional route for it.

public function getFiles()
    {
        $path = public_path('images');
        $files = File::files($path);

        return $files;
    }

In the template, when the event is added, I did to receive updated data via get jQuery:
$.get( "{!! route('your_url') !!}", function( data ) {
                console.log(data);
});

Now the data always comes up to date.

J
jazzus, 2020-10-28
@jazzus

Ajax?) There is also nonsense like Livewire, but I do not recommend it.

P
pLavrenov, 2020-10-29
@pLavrenov

Correctly configure the Echo server and listen for the necessary events.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question