Is there any way to limit users in my project for number of posts. For example, I want my users can create a maximum 10 posts each one. So one user has 10 posts? Is it something with hasMany or something else? Please help find a solution. Thank you
By definition
Middleware provide a convenient mechanism for filtering HTTP requests
entering your application. For example, Laravel includes a middleware
that verifies the user of your application is authenticated. If the
user is not authenticated, the middleware will redirect the user to
the login screen. However, if the user is authenticated, the
middleware will allow the request to proceed further into the
application.
To prevent user from adding more than 10 posts you need to create a middleware to protect your posts/create route
To create a new middleware, use the make:middleware Artisan command:
php artisan make:middleware CheckUserPostsNumber
This command will place a new CheckUserPostsNumber class within your app/Http/Middleware directory. In this middleware, we will only allow access to the posts/create route if the user posts number < than 10. Otherwise, you will redirect the user back to the home URI:
<?php
namespace App\Http\Middleware;
use Illuminate\Support\Facades\Auth;
use Closure;
class CheckUserPostsNumber
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (Auth::user()->posts->count() >= 10) {
return redirect('home');
}
return $next($request);
}
}
Assigning Middleware To Routes
you would like to assign middleware to specific routes, you should first assign the middleware a key in your app/Http/Kernel.php file. By default, the $routeMiddleware property of this class contains entries for the middleware included with Laravel. To add your own, append it to this list and assign it a key of your choosing:
// Within App\Http\Kernel Class...
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
//...
'checkUserPostsNumber' => 'App\Http\Middleware\checkUserPostsNumber'
];
Once the middleware has been defined in the HTTP kernel, you may use the middleware method to assign middleware to a route:
Route::get('posts/create', function () {
//
})->middleware('auth', 'checkUserPostsNumber');
Docs
if ($user->posts->count() >= 10) {
//
}
Related
I want to allow some routes to only respond to requests made by my front-end website, meaning block other sources like postman and allow only the request from domain of the front-end for security reasons.
Is it possible?
for example, I have a webpage to check the dynamic value of the link and verify if the token on link is on database or not, I can think of putting captcha so a bot can't check all possible combinations, but it's not 100% safe.
Laravel API Throttling
if your main problem is bots getting all combinations, the throttling middleware alongside using captchas will help you with that.
By default, all your API routes (in routes/api.php) allow for a maximum of 60 requests per minute per IP. You can modify this amount to your own need in app/Http/Kernel.php file by changing the throttle:api section:
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
changing it to throttle:30:1 for example will mean you will allow 30 requests per minute per ip.
if you only want some routes on your api to be throttled, you can use the middleware elsewhere:
Route::get('my-method', MyController::class)->middleware('throttle:30:1');
Create a middleware that limits hosts
if you want to limit exactly by domain, what you are looking for is probably a custom middleware. Middlewares allow you to inspect various request properties (including the request's host through $request->getHost()) and prevent any controllers or methods.
Although Laravel's default TrustHosts middleware provides a global host validation, you could create your own custom middleware for specific paths that would look like this:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class LocalOnly
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle(Request $request, Closure $next)
{
if($request->getHost() != 'localhost')
{
return response('', 400);
}
return $next($request);
}
}
Note: if you are creating new middlewares, you will need to register them. Laravel has its own guide on this here.
in this example, when used on any route, Laravel will reject any host other than localhost (so even 127.0.0.1 will be rejected)
Personally, I don't recommend doing this as the built-in throttling is a much more elegant solution but in case you really need to do it, here you go.
You can simply do this by creating middleware. I added some more efficient way to add restrications.
1- Create Middleware ApiBrowserRestricationMiddleware
2- Add this \App\Http\Middleware\ApiBrowserRestricationMiddleware::class in
App\Http\Kernel $middleware array
3- Add the code in ApiBrowserRestricationMiddleware
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class ApiBrowserRestricationMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle(Request $request, Closure $next)
{
if(in_array($request->getHost(), ['127.0.0.1']) == false)
{
return response('', 400);
}
return $next($request);
}
}
I'm trying to create a website with multiple languages (with Laravel 5.5). Therefore I follow the tutorial https://mydnic.be/post/how-to-build-an-efficient-and-seo-friendly-multilingual-architecture-for-your-laravel-application, but somehow I have troubles with the language middleware part:
// BeforeLanguage.php
namespace App\Http\Middleware;
use Closure;
class BeforeLanguage
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
// Check if the first segment matches a language code
if (!array_key_exists($request->segment(1), config('translatable.locales')) ) {
// Store segments in array
$segments = $request->segments();
// Set the default language code as the first segment
$segments = array_prepend($segments, config('app.fallback_locale'));
// Redirect to the correct url
return redirect()->to(implode('/', $segments));
}
return $next($request);
}
}
It works if I open a URL with the identifier for the language, e. g. http://ps.dev/de/app/login but I get "Sorry, the page you are looking for could not be found." if I try to open the page without the language identifier in the URI, e. g. http://ps.dev/app/login.
But here I would expect that the middleware adds the language segment to the URI. Any idea what could go wrong?
Below I would like to provide some additional information.
web.php
Route::prefix('app')->group(function () {
// Authentication routes
Route::get('login', 'SessionsController#create')->name('login');
// ...
});
Kernel.php
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\BeforeLanguage::class,
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
According to the Laravel documentation page the middlewares assigned to the middleware group web get executed by default for any route defined inside web.php. (Out of the box, the web middleware group is automatically applied to your routes/web.php file by the RouteServiceProvider.)
RouteServiceProvider.php
protected function mapWebRoutes()
{
$locale = Request::segment(1);
Route::prefix($locale)
->middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
}
I think you had chosen a hard way something like "Reinvent the Wheel!" ;)
Although It's your decision and respectful, as a suggestion try this nice package for localization in Laravel :D
The reason why it is sending to the 404 is that the url doesn't exist. In your route file, you have not created the paths for language. So ultimately, if your
middleware works it will send to the non-existing route path, which will be 404.
Add an identifier for the language :-
Route::get('{lang}/login', 'SessionsController#create')->name('login');
Check you routes by the following artisan command in cmd
php artisan route:list
I am new in learning laravel. Currently I have been stuck in the Laravel Policy,could you please kindly help with directing me how to add policy to my project?
I would like to make just only the Administrator User be able to see the 'Administration Dashboard' by using Laravel Policies Rules but failed. Actually every registered user is able to see that entrance(just like the attached picture showing below).
The user name is uu#gmail.com and the password is uuuuuu.
Please go to my testing website http://lookoko.com/ and log with the user name and password you will see that Administration Dashboard list in the drop-down lists.
To create a new middleware, use the make:middleware Artisan command:
php artisan make:middleware AdminMiddleware
This command will place a new AdminMiddleware class within your app/Http/Middleware directory. In this middleware, we will only allow access to the route if the logged-in user is admin. Otherwise, we will redirect the users back to the home URI.
<?php
namespace App\Http\Middleware;
use Closure;
class AdminMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (! auth()->user()->is_admin) {
return redirect()->route('home');
}
return $next($request);
}
}
Here I am assumming you have a column in user table named is_admin
Registering Middleware
You should assign the middleware a key in your app/Http/Kernel.php file. By default, the $routeMiddleware property of this class contains entries for the middleware included with Laravel. To add your own, simply append it to this list and assign it a key of your choosing. For example:
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
...
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'admin' => \App\Http\Middleware\AdminMiddleware::class,
];
Once the middleware has been defined in the HTTP kernel, you may use the group method to assign middleware to group of routes:
Route::group(['middleware' => ['admin']], function () {
// all your admin routes comes here
});
Docs
I'm not clear with the concept of middleware in Laravel. What does laravel middleware do? Please provide an example if possible.
Middleware is something that is placed between two requests.
Suppose that you need to make sure that when user access to a specific group of routes he/she is authenticated.
There are two option:
Add in every controller the code to check if user is logged in ( in this example we do not consider a parent controller )
Use a middleware
In the first case you should write in each controller the same code.
With the middleware you have a piece of code that you can re-use in multiple section of your application.
Let's suppose that we want to create a Middleware that need to check if the user is logged in:
namespace App\Http\Middleware;
use Closure;
class UserIsLoggedIn
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (!auth()->user()) {
return redirect('home');
}
return $next($request);
}
}
Now with this code we can check our user where we need.
First of all since this is a custom middleware you need to register it in the app/Http/Kernel.php file in the $routeMiddleware property:
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
// ...
'isLoggedIn => \App\Http\Middleware\UserIsLoggedIn::class,
];
Let's assume that you have a group of routes that need to check the user is logged in:
Route::get('admin/profile', function () {
//
})->middleware('isLoggedIn');
Now all the routes in this group will check if the user is logged otherwise he will be redirect to home.
Now assume that you have another controller that need to make sure that the user is logged in, now you can re-use the middleware to do that:
class MyController extend Controller {
function __construct(){
$this->middleware('isLoggedIn');
}
}
So middleware help you to organize the login and re-use pieces of code for specific tasks.
Laravel has a lot of documentation about middleware that you can find here
i have 2 logins pages on my project
1) cms/admin/login
2) cms/users/login
How to redirect if user to user login page
cms/users/login
and if admin call
cms/admin/ redirect to cms/admin/login page
First of all, you don't know if user is user or admin until he logs into your app, so having 2 different routes for same thing is kinda bad. To achieve something similar what you want, you will need to have one cms/login route where user/admin will login and depending on his status (e.g. 1 - user, 2 - admin) you redirect him on cms/user/page or cms/admin/page. To make this you will have to use Middleware which is very good documented in Laravel official documentation.
For example your middleware for all admin pages should look like this
<?php
namespace App\Http\Middleware;
use Closure;
class AdminMiddleware
{
/**
* Run the request filter.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if ($request->input('status') == 2) {
//2 means its admin and i let him get that admin page
return $next($request);
}
//he is not admin so i redirect him back
return Redirect::back();
}
}
In Kernel.php you add middleware alias
protected $routeMiddleware = [
'admin' => \App\Http\Middleware\AdminMiddleware::class,
];
And in routes.php you assign middleware to that routes
Route::get('/cms/admin/page', ['middleware' => 'admin', 'uses'=>'Controller#method']);
Hope it helps