Reputation: 860
is it possible in Laravel to show a view within a Controller function without stopping that functions logic/process?
What I mean is, when I access this specific route (via. GET Method), the user is presented with a blank white screen for about 10 seconds while a good amount of logic is ran before redirecting to a new view. How can I show a view while that logic runs?
EXAMPLE:
protected function callback(Request $request)
{
// - LOGIC DONE HERE WHICH CALLS ABOUT 3 SUBSEQUENT FUNCS, WHICH
// TAKES LONGER THAN USUSAL
// - I WANT TO RETURN A VIEW HERE IN THE MEANTIME WHILE LOGIC RUNS
// WITHOUT HALTING THE PROCESS SO USER WONT BE SUBJECT TO JUST PLAIN
// WHITE SCREEN FOR EXTENDED PERIOD OF TIME
}
How would I go about doing so?
Upvotes: 0
Views: 982
Reputation: 1502
Once you responded the blank page then the PHP request is dead. It must involves some sort of front-end mechanism in order to achieve what you want.
For example, using AJAX.
// HomeController
public function index() {
return view('home');
}
// home.blade.php
function getMessage() {
$.ajax({
type:'POST',
url:'/getmsg',
data:'_token = {{ csrf_token() }}',
success:function(data) {
$("#msg").html(data.msg);
}
});
}
$(document).ready(function () {
getMessage();
}
If you need to process a task that takes a long time(let's say few minute) and you don't want user to wait for the response, you can use Queue and broadcast to front-end and return the view to ask user to wait first.
// HomeController
public function index() {
MailJob::dispatch();
return view('home');
}
// MailJob
public function handle() {
// job logic
broadcast(new MailSent); // Notify front-end the event
}
Then the MailSent
event will be broadcasted to front-end. You then listen to the event using the Laravel Echo
in your frontend.
These Queue and Broadcast requires quite some time to setup if you're not familiar. Use it wisely.
Upvotes: 1
Reputation: 4558
That is not possible, due to how server/client/requests works. Perhaps you can solve it like this. Have only ONE view, with a default loader HTML element, something like a spinner gif. Then you put something like this piece of JS to run as soon as your page is loaded
fetch('/api/your-logic-process')
.then((response) => response.json())
.then(function(data) {
//hide the loading element
//render the results
})
This assumes you have an API route /api/your-logic-process
where you can handle your time consuming tasks.
Upvotes: 1