I'm trying to block a route where the logged-on user's ID is not the same as the route of the object he's trying to edit.
Example :
I am in charge of administering different buildings assigned to me with the key "user_id" in the database (in the building table). I am demonic and I want to go change the sheet of a building that I do not mind. By taking the URL, I can go to modify the building of my enemy.
I create a relation in my model Building
public function owner()
{
return $this->belongsTo(User::class, 'id', 'user_id');
}
And a middleware
use App\Models\Building;
use Closure;
use Auth;
class CheckOwnItem
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ( Auth::id() != Building::class->user_id){
abort(403);
}
return $next($request);
}
}
When I want to access my route with the middleware 'building', I have an error. I think that I don't access correctly the data of my buildings. How to do ?
Parse error: syntax error, unexpected '->' (T_OBJECT_OPERATOR)
Thank you !
You need to retrieve a building instance and then do the checking.
Something like this maybe:
public function handle($request, Closure $next)
{
$building = Building::find($request->id);
if ( Auth::id() != $building->user_id){
abort(403);
}
return $next($request);
}