Showing posts with label Middleware. Show all posts
Showing posts with label Middleware. Show all posts

Friday, February 8, 2019

Middleware when running Artisan console request

I want a custom piece of middleware to run whenever I run an artisan command. I need to set a few environment variables to be used in the app configuration before the actual command executes.
There is a way around but not sure if the correct one, but works. Just open up the Kernel class and override the bootstrap method. Laravel 5.3, have not tested on other versions, but should work similarly
<?php
namespace App\Console;

use Log;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        Commands\Inspire::class,
    ];

    public function bootstrap() {
        parent::bootstrap();
        Log::info("KERNEL COMMAND EXECUTING");
    }

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->call('App\Service\YourService@method')->dailyAt('10:00');

        $schedule->call('App\Service\YourService@method')->everyFiveMinutes();
    }
}
And finally the Kernel is executed by CronJob or Laravel Jobs.
To add Laravel kernel scheduler to CronJob, execute command crontab -e and add below line and save the operation.
* * * * * /usr/local/bin/php /project_location/www/project/artisan schedule:run >> /dev/null 2>&1

Sunday, June 25, 2017

Laravel 5: Use of Laravel Middleware WEB | API | THROTTLE

You have to create a middleware first. Create a php file named "ApiFilter.php" in "app/Http/Middleware" folder with following contents:


<?php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\Request as HttpRequest;

class ApiFilter
{
    protected $auth;

    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
    }

    public function handle(HttpRequest $request, Closure $closure)
    {
        if ($this->auth->guest()) {
            if ($request->ajax()) {
                return response('Unauthorized.', 401);
            }
            else {
                return redirect()->guest('login');
            }
        }
        return $closure($request);
    }
}


Now you have to register this middleware to your project. Need to open "App\Http\Kernel.php" file. If you want to register this middleware for global scope then you have to add the below line as follows:


protected $middleware = [
    \App\Http\Middleware\ApiFilter::class
];


So when you browse any url in your project scope, this middleware can handle them.

But if you want to the middleware for specific area you have to add the middleware to "$middlewareGroups" as follows:


protected $middlewareGroups = [
    'web' => [
        .....
    ],

    'api' => [
        'throttle:3,1',
        \App\Http\Middleware\ApiFilter::class
    ],
];


Now add the following lines to "app\Http\routes.php":


Route::group(["middleware" => "api", "prefix" => "api"], function() {
    Route::get('action_name', 'ApiController@action_name');
});


If you browse "www.domain.com/api/action_name" it will pass through ApiFilter middleware bacause of prefix "api" used. But if you only browse "www.domain.com/action_name" it will pass through another middleware.



These middleware may be assigned to groups or used individually


protected $routeMiddleware = [
    'my_middleware' => \App\Http\Middleware\Authenticate::class
];

And can be used as below:

Route::group(['middleware' => 'my_middleware'], function() {
    Route::get('landing-page', 'MyController@landingPage');
});


We can use "throttle" which will restrict request overloading. Here we used "throttle:3,1" means per minute 3 request can be granted, if more request send request rejected as below image:

We need to add below line to "routeMiddleware" for "throttle" action:


protected $routeMiddleware = [
    .........,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];