user4074875
user4074875

Reputation: 146

Laravel 5.2 route model binding error causing SQL unknown column error

I'm trying to implement this package- https://github.com/vinkla/hashids to obsfucate all ids in URLs.

I've created a fresh install of laravel 5.2 and created one model called Orange.php with table populated-

INSERT INTO `oranges` (`id`, `orange_name`) VALUES(1, 'test1'),(2, 'test2'),(3, 'test3');

I added the following to routes.php-

Route::bind('id', function ($id, $route) {
return Hashids::decode($id)[0];
});

Route::resource('orange', 'OrangeController');

Route::model('orange', 'App\Orange');

I also overrided getRouteKey by adding the following function to Orange.php-

public function getRouteKey()
{
return Hashids::encode($this->getKey());
}

So getRouteKey should encode the ID to displaying the URL,eg 3 goes to hgfdh, then my route binding should apply itself via the 'id' wildcard to any route using id parameter to decode the ID for OrangeController.php in this case.

I received the following two errors when attempting to load http://localhost:8000/orange/3-

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'orange_name:"test3"' in 'where clause'

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'orange_name:"test3"' in 'where clause' (SQL: select count(*) as aggregate from `oranges` where `orange_name` = test3 and `orange_name:"test3"` <> {"id":3 and `created_at:"2016-06-23 09:30:39"` = updated_at:"2016-06-23 09:30:39"})

I think this error relates to-

 Route::model('orange', 'App\Orange');

Is it attempting to bind an instance of Orange instead of $id of Orange? If so how can I bind on $id?

if I comment out the Route::model definition I get-

NotFoundHttpException in Handler.php line 103:
No query results for model [App\Orange].

Upvotes: 2

Views: 323

Answers (1)

Gino Pane
Gino Pane

Reputation: 5011

Laravel has "route-model" binding mechanism. So in your route you could expect an obfuscated id, but in bind method you should get a proper model instance, like that:

Route::bind('orange', function($value)
{
    $id = Hashids::decode($value)[0];

    return Orange::findOrFail($id);
});

Here's a nice example that may help.

Upvotes: 0

Related Questions