Laravel: why every route is executed twice? - laravel

In my laravel app, I noticed that every route is executed twice, and can't figure out why
for example:
Route::get('called_twice', function () {
dump('---');
});
return string '---' twice
Edit:
trying to backtrace the source of the issue, I put a dump in file
src/Illuminate/Foundation/Http/Kernel.php
protected function sendRequestThroughRouter($request)
{
$this->app->instance('request', $request);
Facade::clearResolvedInstance('request');
$this->bootstrap();
dump('kernel');
return (new Pipeline($this->app))
->send($request)
->through($this->app->shouldSkipMiddleware() ? [] : $this->middleware)
->then($this->dispatchToRouter());
}
and another dump in the constructor of the file
src/Illuminate/Pipeline/Pipeline.php
public function __construct(Container $container = null)
{
dump('pipeline');
$this->container = $container;
}
and I get this:
the Pipeline class is called many time
Laravel 6.8.0

I think $next($request) is probably called twice in a middleware. The reason is that the response is passed throught each middleware (pipes) before it is returned back.
So if $next($request) is called twice in one middleware it is normal that all pipes will be called again.

Found mine in the master. there was a script that was causing the page to reload in the background.
I built a little counter with admin access only and smoked it out. Came down to one script.

Related

Laravel Nova - Observer Update Method Causes 502

When trying to update a resource in Laravel Nova that has a Observer the update loads for a while and then ends with a 502 error. The observer is registered correctly (the created method works fine) and I'm not trying to do anything special in the updated method. Any ideas?
public function updated(Model $model)
{
//
$model->title = 'test';
$model->save();
}
If I try this without the $model->save(), there is no 502 error but the change I want to happen also doesn't happen. I get the green success message, and any change I make on the form prior to updating occurs, but not the change I'm trying to make during the updated method.
Any help troubleshooting this would be appreciated
I am not very good at Laravel, but I think, that you should to try this:
In your model file add method:
public function saveQuietly(array $options = [])
{
return static::withoutEvents(function () use ($options) {
return $this->save($options);
});
}
Then, in your updated method in observer do something like this:
public function updated(Model $model)
{
$model->title = 'test';
$model->saveQuietly();
}

¿Event after the end of delivering the response to the user?

Well basically what I need is to delete some files from the storage folder, but I want that to happen every time a request is finished.
I have already created an event and a listener that is responsible for doing that, which is called before doing the return in the controller. But since some exception may happen, the event is obviously not going to be launched.
I need that to always run regardless of whether an exception occurs or not.
The laravel documentation https://laravel.com/docs/4.2/lifecycle#application-events talks about it but it is in version 4.2 and that does not have the current version
Use the AfterMiddleware:
This middleware would perform its task after the request is handled by the application:
class AfterMiddleware
{
public function handle($request, Closure $next)
{
$response = $next($request);
// Perform action
return $response;
}
}
https://laravel.com/docs/5.5/middleware#defining-middleware

How to send a response from a method that is not the controller method?

I've got a Controller.php whose show($id) method is hit by a route.
public function show($id)
{
// fetch a couple attributes from the request ...
$this->checkEverythingIsOk($attributes);
// ... return the requested resource.
return $response;
}
Now, in checkEverythingIsOk(), I perform some validation and authorization stuff. These checks are common to several routes within the same controller, so I'd like to extract these checks and call the method everytime I need to perform the same operations.
The problem is, I'm unable to send some responses from this method:
private function checkEverythingIsOk($attributes)
{
if (checkSomething()) {
return response()->json('Something went wrong'); // this does not work - it will return, but the response won't be sent.
}
// more checks...
return response()->callAResponseMacro('Something else went wrong'); // does not work either.
dd($attributes); // this works.
abort(422); // this works too.
}
Note: Yes, I know in general one can use middleware or validation services to perform the checks before the request hits the controller, but I don't want to. I need to do it this way.
As of Laravel 5.6 you can now use for example response()->json([1])->send();.
There is no need for it to be the return value of a controller method.
Note that calling send() will not terminate the output. You may want to call exit; manually after send().
You are probably looking for this:
function checkEverythingIsOk() {
if (checkSomething()) {
return Response::json('Something went wrong');
}
if(checkSomethingElse()) {
return Response::someMacro('Something else is wrong')
}
return null; // all is fine
}
And in the controller method:
$response = $this->checkEverythingIsOk();
if($response !== null) { // $response instanceof Response
return $response;
}
It's probably overkill, but I will throw it in anyway. You might want to look into internal requests. Also this is just pseudoish code, I have not actually done this, so take this bit of information with caution.
// build a new request
$returnEarly = Request::create('/returnearly');
// dispatch the new request
app()->handle($newRequest);
// have a route set up to catch those
Route::get('/returnearly', ...);
Now you can have a Controller sitting at the end of that route and interpret the parameters, or you use multiple routes answered by multiple Controllers/Methods ... up to you, but the approach stays the same.
UPDATE
Ok I just tried that myself, creating a new request and dispatching that, it works this way. Problem is, the execution does not stop after the child-request has exited. It goes on in the parent request. Which makes this whole approach kind of useless.
But I was thinking about another way, why not throw an Exception and catch it in an appropriate place to return a specified response?
Turns out, thats already built into Laravel:
// create intended Response
$response = Response::create(''); // or use the response() helper
// throw it, it is a Illuminate\Http\Exception\HttpResponseException
$response->throwResponse();
Now usually an Exception would be logged and you if you are in Debug mode, you would see it on screen etc. etc. But if you take a look into \Illuminate\Foundation\Exceptions\Handler within the render method you can see that it inspects the thrown Exception if it is an instance of HttpResponseException. If it is then the Response will be returned immediately.
To me the most simple and elegant way is:
response()->json($messages_array, $status_code)->throwResponse();
(you don`t need return)
It can be called from a private function or another class...
I use this in a helper class to check for permissions, and if the user doesn`t have it I throw with the above code.

Getting Queued Jobs response Laravel 5.2

currently I have the following set up, a route that is calling a function in my controller that is in turn queuing a job.
//My Route
Route::get('/testJob', 'Controller#testJob');
//My Controller
public function testJob()
{
$job = (new testJob())->delay(5);
$this->dispatch($job);
}
//My job
public function handle()
{
require 'testAPICall.php';
// echo $response;
return $response;
}
//testAPICall.php
$response = 'this is the response';
//Queue After
Queue::after(function (JobProcessed $event) {
echo var_dump($event->data);
});
What I would like to be able to do, is access the response returned by the job in Queue::after, or alternatively, pass a callback into the queue to be execute after the job, again with access to the response from the job.
Is this something that is possible with Laravel Queues, and if so how would I go about this?
Cheers, Jack.
Queue::after() is a global callback, that will run after each job. So this might not what you want.
In your case, I would depend on Events/Listeners to be triggered after finishing the job.
public function handle(Mailer $mailer)
{
//Your code
event(new JobDone($data));
}
Please let me know if you need more details for implementation.
I have done something like yours that log a message "queue.txt" in laravel 5 "app" folder
This code I've got from a youtube video and not my code , but I have tested it successfully
First thing you have to code in "Routes.php" as below
Route::get('/',function()
{
//$queue = Queue::push('LogMessage',array('message'=>'Time: '.time()));
$queue = Queue::later(20,'LogMessage',array('message'=>'Time: '.time()));
return $queue;
});
class LogMessage{
public function fire($job,$data){
File::append(app_path().'/queue.txt',$data['message'].PHP_EOL);
$job->delete();
}
}
Then you can run your project folder using "php -S localhost:8888 -t public"
at the same time you must open a another terminal window in windows or linux environment and pointed to same folder and issue the command "php artisan queue:listen"
I think this will be helpful for you!

redirect is not working in codeigniter _construct function

I am facing a problem using redirect in _construct function,
In timesheet controller I wrote the following code and I am getting an error in the browser "
This problem can sometimes be caused by disabling or refusing to
accept
cookies.
Here is my code
class Timesheet extends MY_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('timesheet_model');
//$this->load->library('auth');
$username=$this->session->userdata('logged_in');
//$this->load->model('login_model');
if($username['fullname']!=""){
redirect('timesheet');
}
else{
redirect('login');
}
}
Please help me to find a way to get rid of this problem.
Thanks.
It looks to me like you're going around in a loop.
You check to see if the fullname element in your $username array is empty and, if it is, you redirect back to the same controller. I'm willing to bet it goes around in a circle like that for a while before the webserver throws up the error you mention.
If I'm reading what you're trying to do correctly, wouldn't you call another function within your Timesheet constructor if the fullname element is present to show whatever information it is that you're trying to display?
I'd suggest changing your logic to do the following:
if($username['fullname'] == ""){
redirect('login');
}
else{
//go to another controller method here
}
OK. I got it. The error is just because of I am redirecting to same controller where I have written the code. Everytime when it redirects to timesheet it enters into the construct function and it redirects again to timesheet. And the same thing is working like an endless loop.
So the fault was redirecting to the same controller.
I
use redirect like this : redirect('timesheet', 'refresh');

Resources