Neo
Neo

Reputation: 561

laravel 5.1 - trait boot not being called for model::update() function

I have created trait as follows on this page app/Traits/ModelEventThrower.php

namespace App\Traits;

use Input;
use Event;
use App\Events\ActivityLog;
use Illuminate\Database\Eloquent\Model;
//use Illuminate\Support\Facades\Event;

/**
 * Class ModelEventThrower 
 * @package App\Traits
 *
 *  Automatically throw Add, Update, Delete events of Model.
 */
trait ModelEventThrower {

    /**
     * Automatically boot with Model, and register Events handler.
     */
    protected static function bootModelEventThrower()
    {

        foreach (static::getModelEvents() as $eventName) {

            static::$eventName(function (Model $model) use ($eventName) {
                try {

                    $reflect = new \ReflectionClass($model);

                    echo "here";exit;

                  } catch (\Exception $e) {
                    return true;
                }
            });
        }
    }

    /**
     * Set the default events to be recorded if the $recordEvents
     * property does not exist on the model.
     *
     * @return array
     */
    protected static function getModelEvents()
    {
        if (isset(static::$recordEvents)) {
            return static::$recordEvents;
        }

        return [
            'created',
            'updated',
            'deleted',
        ];
    }
}

My City Model is something like this

namespace App;

use App\Traits\ModelEventThrower;
use App\Events\ActivityLog;

use Illuminate\Database\Eloquent\Model;
use Event;

class City extends Model
{
    use ModelEventThrower;
    //protected static $recordEvents = ['updated'];
...
}

My CitiesController is

namespace App\Http\Controllers\Admin;

use App\City;
use App\Country;
use Input;
use Validator;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class CitiesController extends Controller
{
......
    public function update(City $city,Request $request)
    {
     ......
    $city->where('id','=',$input['id'])->update($input);

Somehow, I dont see its calling the function written in trait file. When I tried to create $city->create($input); it echos "here" and stops execusion, but not doing same for update function , however I could successfully update the records.

Any suggestion/help will be highly appreciated.

Upvotes: 2

Views: 2590

Answers (1)

vnay92
vnay92

Reputation: 318

I had a similar issue with Laravel. By adding a constructor in the model to call the boot() function of the parent Model, like so:

public function __construct()
{
    parent::boot();
}

you can make sure that all the traits are booted. This solved it for me.

Upvotes: 2

Related Questions