How to make Laravel use my class instead of native PDO?


I'm facing a big problem here. I work using laravel 5.1 and Sql Server 2012. The problem is: All tables of my database have a trigger that is responsible to log activities on that table. This trigger do a insert after the insert on the main table. This way, every time I insert a new Person, the trigger will insert a new PersonLog.

This way, on Laravel when I do:

$person = Person::create(['personName' => 'Anderson']);
echo $person->id; //it tries to show me the log id instead of person id.

It happens because PDO uses @@identity variable to search for the last inserted id instead of use SCOPE_IDENTITY().

Solutions: - I tried a pull request on laravel source using a manual query instead of pdo lastInsertId() method. It was denied. - The another solution is create a class extending PDO and make laravel use my class instead of native pdo. But I don't have any idea of how to do it.

Can you guys help me? Thank you!




I solved it! It was really easy by the way, and I can't imagine how I didn't think on it. What did I do? Let me explain:

  • First, I created a child from SqlServerGrammar inside my project
  • In my SqlServerGrammar I override the compileInsert method
  • In my AppServiceProvider on the boot method, I changed the grammar my connection use, this way: \DB::connection()->setQueryGramar(app(App\Classes\MyCustom\SqlServerGrammar::class));