1

What I want to achieve is, I have audience in a few countries. I also have editors in different country.

For example, editor in US can only edit & view posts in US, editor in Hong Kong not allowed to view US posts.

Route::get('{country}/posts', [
    'uses' => 'CountryController@posts',
    'middleware' => ['permission:view posts,{country}'], <------- SEE HERE
]);

Is it possible to achieve this?

P/S: I'm using Spatie laravel-permission

apokryfos
  • 38,771
  • 9
  • 70
  • 114
Js Lim
  • 3,625
  • 6
  • 42
  • 80

2 Answers2

1

It's easier to create another middleware, something like this:

namespace App\Http\Middleware;

use Closure;

class CountryCheck
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // The method `getEnabledCountries` returns an array 
        // with the countries enabled for the user
        if(in_array($request->route('country'), Auth::user()->getEnabledCountries())) {
           return $next($request);
        }

        // abort or return what you prefer

    }
}

Anyway... the country parameter is useless in my advice if the user can see only posts from his country... If you already know the user locale and you already have this rule... why you have to made another check?

In my opinion it's better to create a route like Route::get('posts') and inside the controller load the posts related to the user's country... Something like:

Post::where('locale', '=', Auth::user()->locale())->get()

or with a scope:

Post::whereLocale(Auth::user()->locale())->get()

IlGala
  • 3,331
  • 4
  • 35
  • 49
  • 1
    Thanks, but `$request->route('country')` is good enough for me. I have idea how to do it already – Js Lim Aug 17 '18 at 07:55
0

It's not possible, but I use this lines of code in a middleware:

$country = $request->route('country'); // gets 'us' or 'hk'

This method of Request returns the route segment.

floflock
  • 586
  • 4
  • 11