mardi 1 septembre 2015

Laravel/Eloquent attach() method bypasses my multitenant trait

I am using the Eloquent attach() method to insert relational data into a pivot table:

$this->user->roles()->attach($role, ['user_id' => $user]);

The above line inserts data into a pivot table linking users and their roles within my app.

The problem is that I have a trait setup to insert a cust_id value into the database table every time a query is executed. The cust_id value never gets inserted when I use the attach method. However, it works with all other methods such as create, insert etc.

My trait file:

<?php 

namespace App\Scopes;
use Session;

trait MultiTenantTrait
{
    /**
     * Constructor.
     * 
     * @return void
     */
    public function __construct($attributes = array())
    {
        parent::__construct(array_merge($attributes, ['cust_id' => Session::get('cust_id')]));
    }

    /**
     * Append `cust_id` to all insert statements.
     * 
     * @return void
     */
    public function insert($attributes = array())
    {
        foreach($attributes as $key => $value) 
        {
            $attributes[$key]['cust_id'] = Session::get('cust_id');
        }

        return parent::insert($attributes);
    }

    /**
     * Boot the scope.
     * 
     * @return void
     */
    public static function bootMultiTenantTrait()
    {
        static::addGlobalScope(new MultiTenantScope());
    }

    /**
     * Get all tenants.
     * 
     * @return string
     */
    public static function allTenants()
    {
        return (new static())->newQueryWithoutScope(new MultiTenantScope());
    }
}

The problem is that the insert() method in my trait (above) is not being triggered. Does anyone know why?

Is there a workaround?

PS - Before you ask, I have use MultiTenantTrait at the top of all models.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1KD1usA
via IFTTT

Aucun commentaire:

Enregistrer un commentaire