Laravel validation site belongs to user -
my user.php
class user extends authenticatable { public function sites() { return $this->hasmany(site::class); } }
my site.php
class site extends model { public function user() { return $this->belongsto(user::class); } }
my routes.php
route::resource('site', 'sitecontroller');
my sitecontroller.php
class sitecontroller extends controller { public function edit(int $id) { $site = auth::user()->sites()->find($id); return view('site.edit', compact('site')); } }
how can validate site belongs user? understand in case if site doesn't belong user, $site
variable null. want more declarative way, laravel requests, because need same check in show
, update
, , destroy
methods. cannot use laravel request, because checking this
$siteid = route::current()->param('site'); $ids = auth::user()->sites()->pluck('id')->toarray(); $result = in_array($siteid, $ids);
can suggest how achieve goal?
since use laravel 5.2, solution route filters deprecated. instead route filter should use middleware.
app/http/middleware/restrictpermission.php
class restrictpermission { public function handle($request, closure $next) { $siteid = route::current()->parameter('site'); if (!auth::user()->sites()->find($siteid)) { abort(403); } return $next($request); } }
app/http/kernel.php
class kernel extends httpkernel { protected $routemiddleware = [ 'restrict.permission' => restrictpermission::class, ]; }
sitecontroller.php
class sitecontroller extends controller { public function __construct() { $this->middleware('restrict.permission', ['except' => [ 'index', 'create', 'store', ]]); } public function edit(int $id) { $site = auth::user()->sites()->find($id); return view('site.edit', compact('site')); } }
Comments
Post a Comment