migrate to gtea from bistbucket
This commit is contained in:
@@ -0,0 +1,87 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Modules\RestaurantDelivery\Traits;
|
||||
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Modules\Authentication\Models\Restaurant;
|
||||
|
||||
trait HasTenant
|
||||
{
|
||||
/**
|
||||
* Boot the trait and add global scope for restaurant_id
|
||||
*/
|
||||
public static function bootHasRestaurant(): void
|
||||
{
|
||||
// Global scope: filter by restaurant_id automatically
|
||||
static::addGlobalScope('restaurant', function (Builder $builder) {
|
||||
if (! config('restaurant-delivery.multi_restaurant.enabled')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$restaurantId = static::getCurrentRestaurantId();
|
||||
if ($restaurantId) {
|
||||
$builder->where('restaurant_id', $restaurantId);
|
||||
}
|
||||
});
|
||||
|
||||
// Auto-fill restaurant_id on creating
|
||||
static::creating(function ($model) {
|
||||
if (! config('restaurant-delivery.multi_restaurant.enabled')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$column = config('restaurant-delivery.multi_restaurant.restaurant_column', 'restaurant_id');
|
||||
|
||||
if (empty($model->{$column})) {
|
||||
$model->{$column} = static::getCurrentRestaurantId();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current restaurant ID from request, auth, or session
|
||||
*/
|
||||
public static function getCurrentRestaurantId(): ?int
|
||||
{
|
||||
// Option 2: From authenticated user
|
||||
if (auth()->check() && method_exists(auth()->user(), 'getRestaurantId')) {
|
||||
return auth()->user()->getRestaurantId();
|
||||
}
|
||||
|
||||
// Option 3: From session
|
||||
if (session()->has('restaurant_id')) {
|
||||
return session('restaurant_id');
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the global restaurant scope
|
||||
*/
|
||||
public function scopeWithoutRestaurant(Builder $query): Builder
|
||||
{
|
||||
return $query->withoutGlobalScope('restaurant');
|
||||
}
|
||||
|
||||
/**
|
||||
* Query explicitly for a specific restaurant
|
||||
*/
|
||||
public function scopeForRestaurant(Builder $query, int $restaurantId): Builder
|
||||
{
|
||||
return $query->withoutGlobalScope('restaurant')
|
||||
->where(config('restaurant-delivery.multi_restaurant.restaurant_column', 'restaurant_id'), $restaurantId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Relationship to Restaurant model
|
||||
*/
|
||||
public function restaurant()
|
||||
{
|
||||
$restaurantModel = config('restaurant-delivery.multi_restaurant.restaurant_model', Restaurant::class);
|
||||
|
||||
return $this->belongsTo($restaurantModel, 'restaurant_id');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user