This expression(terminate) is used for which purpose? - laravel

My terminate middleware as below:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Log;
class ExampleMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next, $role)
{
if ($role == null) {
return redirect('/deneme');
}
return $next($request);
}
public function terminate($request, $response)
{
sleep(4);//what is the purpose in this section(What this means is that anyone who has used this way?)
}
}
What is the purpose of the terminate function, what is it and when should it be used?

Sometimes a middleware may need to do some work after the HTTP response has been prepared. For example, the "session" middleware included with Laravel writes the session data to storage after the response has been fully prepared. If you define a terminate method on your middleware, it will automatically be called after the response is ready to be sent to the browser.
Terminable Middleware

Related

Laravel 8: GET params can't be accessed in Middleware's Request's inputs

I have defined this route in the web.php route file:
Route::get('/middleware_test_user_project_change/{pro_id}/{projet_id}', function ($pro_id, $projet_id) {
return 'test';
})->middleware('user.project.change');
I have defined this handle function in my middleware (which I've added into the kernel with the following entry: 'user.project.change' => \App\Http\Middleware\CheckUserProposition::class):
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use App\Models\User;
class CheckUserProposition
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle(Request $request, Closure $next)
{
$projet_id = $request->input('projet_id');
$pro_id = $request->input('pro_id');
return $next($request);
}
}
However, both $projet_id and $pro_id return NULL when I access the following URL: https://XYZ/middleware_test_user_project_change/1/1
As I've correctly set up the middleware and the routes parameters (which are, finally, GET variables), why can't I use them in my middleware as request inputs?
Route parameters are not part of the 'inputs'. They are a separate thing; this is why you don't see them when you get all the inputs with $request->all().
If you want a route parameter you should probably explicitly ask for it:
$request->route('projet_id');
$request->route()->parameter('projet_id');

Laravel redirection to https

Hi i ve an app made with laravel and this address http://example.com/check/.
I wanted to redirect to https so i created this middleware
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\App;
class HttpsProtocol
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (!$request->secure()) {
return redirect()->secure($request->getRequestUri());
}
return $next($request);
}
}
Then i added
\App\Http\Middleware\HttpsProtocol::class
to Kernel in App/Http in protected $middlewareGroups
Redirection seems to work but redirect to this address https://example.com/check/check
with repeated URI (check)
Why
Thx a lot
It looks like you don't need to append the request URI, that is happening already so try:
if (!$request->secure()) {
return redirect()->secure();
}

Assigning middleware inside a Middleware handle function in Laravel

I want to know If it is possible to assign a middleware or execute a middleware in handle function of another middleware
<?php
namespace App\Http\Middleware;
use Closure;
class AuthTypeMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if($request->header('auth_type') === "api") {
// execute the auth:api middleware here
}
else {
// execute the auth middleware here
}
}
}
I know we can achieve this by creating different route groups with prefix but still I wanted to know if their any possibility of getting this work

Return every request as plain json Laravel using Middleware

I have a route in my web.php that returns a view:
Route::get('/', function () {
return view('welcome');
});
welcome is default Laravel view welcome.blade.php.
I have Middleware called AlwaysReturnJson and it contains:
<?php
namespace App\Http\Middleware;
use Closure;
class AlwaysReturnJson
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$request->headers->set('Accept', 'application/json');
return $next($request);
}
}
I set up this middleware in Kernel.php as global middleware:
protected $middleware = [
\App\Http\Middleware\AlwaysReturnJson::class
];
What I expect is to get plain text/json of welcome file in my browser when I navigate to given route but I always get it as html and it render page properly. I checked it, it applies middleware on every request so that is not a problem. Why is this happening and shouldn't it convert that view to a plain text? Am I doing something wrong?
If you want to set a header for your response you can do this:
namespace App\Http\Middleware;
use Closure;
class AlwaysReturnJson
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
$response->headers->set('Content-Type', 'application/json');
return $response;
}
}
If you want to force return valid json content use this middleware instead:
namespace App\Http\Middleware;
use Closure;
class AlwaysReturnJson
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
return response()->json($response->getContent());
}
}
See Laravel docs about after middleware for more info.
You can alternatively return json response on your controller without any middleware needed:
Route::get('/', function () {
return response()->json(
view('welcome')->render()
);
});
You may want to use laravel After middleware (the middleware would perform its task after the request is handled by the application) and then set the content-type of response.
<?php
namespace App\Http\Middleware;
use Closure;
class AfterAlwaysReturnJson
{
public function handle($request, Closure $next)
{
$response = $next($request);
return $response->header('Content-Type', 'application/json');
}
}

How to log responses of an api request in terminate function of a Laravel middleware

I need to log responses of each api request. For that I created a middleware and used ResponseTrait in terminate function of that middleware. Everything works fine until I use the status function of ResponseTrait. I tried both $this->status and self::status but nothing worked. It says syntax error when I use this function. Following is the code of my middleware.
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
use Spatie\HttpLogger\LogWriter;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\ResponseTrait;
class logger implements LogWriter
{
use ResponseTrait;
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
return $next($request);
}
public function terminate($request)
{
$responseCode = $this->status();
}
}
The response status comes from the result of $next($request);, so you'd need to reference it like:
$response = $next($request);
$status = $response->status();
return $response;

Resources