Skip to content
Advertisement

Laravel 9 query builder where clause has empty model id

I’m working on a Laravel 9 project and have created a custom validation rule called ValidModelOwnership which should check that the field a user is trying to add is owned by a model based on some values passed to it.

I’ve written the rule, but when debugging and outputting $model->toSql() the id is empty?

What am I missing?

My rule:

And my usage in my controller:

I’ve hard-coded my id’s to illustrate that even when set statically, it’s not passed through:

[2023-01-19 09:40:59] local.DEBUG: select * from products where (company_id = ?) and products.deleted_at is null

Advertisement

Answer

Laravel (and most other frameworks) extract out variables when building SQL queries to prevent SQL injection.

So the following eloquent query:

will become:

and it will also pass an array of bindings: ['Larry']. When SQL processes the query it replaces replaces the ? with the values in the bindings.

So if you want to see the full query you need to log the SQL and the bindings:

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement