Reputation: 75
Is it possible to create a middleware in laravel 5.2x to return data in controller only for specific user_id instead typing everywhere stuff like
->where('access_gallery','=',true)
For example I have a gallery on my webpage where users can upload photos crop them etc.
I check by middleware if their payment_datetime < current datatime, if true next step.
In next step i want to return/edit/delete/crop/..., only photos for specific user, to do that normally i would have to create a query with @up code, because we I dont want user_1 to edit user_2 page.
It's a little annoying to copy it everywhere, and also if i create an Admin account to access everything i have to create next query for every each function to return all data for them.
If it's not possible to create function like that in middleware, is it possible in controller?
Upvotes: 2
Views: 477
Reputation: 5367
I think what you're looking for is a scope - or even a global scope. https://laravel.com/docs/5.2/eloquent#global-scopes
Create a Scopes
directory under App
. Create a file like so:
<?php
namespace App\Scopes;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
class UserGallery implements Scope
{
/**
* Query if user has gallery
*
* @return void
*/
public function apply(Builder $builder, Model $model)
{
return $builder->where('access_gallery','=',true);
}
}
Then in your model (that you want this scope applied too), add a boot
function to the beginning of your model class:
use App\Scopes\UserGallery;
/**
* The "booting" method of the model.
*
* @return void
*/
protected static function boot()
{
parent::boot();
static::addGlobalScope(new UserGallery);
}
You could even put the scope in a trait
class...in my opinion, would look cleaner and easier to inject into your models.
PS: Limit the amount of logic you put in a middleware class. Consider middleware as a door to get into your main set of logic. That door is either open or locked for the user to access.
Upvotes: 2