3

i am using the resource in laravel when I get the data its ask me for the id but the primary key in my table is user_menu_id how to change the using resource route

route

Route::resource('/UserMenuController', 'UserMenuController');

error

Unknown column 'user_menus.id' in 'where clause' (SQL: select * from user_menus where user_menus.id = 1 limit 1)

enter image description here model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class user_menu extends Model
{

 protected $fillable = ['menu_parent_id', 'menu_title', 'menu_class', 
'menu_id', 'menu_link', 'created_by', 'updated_by', 'created_at', 'updated_at'];
}
Sam
  • 151
  • 1
  • 1
  • 9

4 Answers4

1

The error says there is not a table with named user_menus. Set the real table name $table property in the model:

protected $table = 'user_menu';

Or you may follow Laravel naming conventions as described in my repo and just rename the table to user_menus (plural for user_menu class).

You said the primary key is not standard too, so change it too to $primaryKey:

protected $primaryKey = 'user_menu_id';
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
  • in my table primary key name is user_menu_id but it asking for id i need to change that id – Sam Jan 26 '18 at 11:21
  • Ok, then my original answer was correct, just add `$primaryKey`. Also, is the table name `user_menu` or `user_menus`? – Alexey Mezenin Jan 26 '18 at 11:23
1

Define the primary key in your model class and you will be golden.

The reason you're encountering an error is due Laravel always assuming the primary key is id. Reading the error log, you will notice:

1054 Unknown column 'user_menus.id' - you can right away know it's trying to find a non-existent column.

The fix will is to assign $primaryKey to your model class, e.g:

protected $primaryKey = 'user_menu_id';

Shafiq al-Shaar
  • 1,292
  • 14
  • 22
1

According to this article, you need to override $primaryKey property:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class user_menu extends Model
{
    protected $fillable = [
        'menu_parent_id', 'menu_title', 'menu_class', 
        'menu_id', 'menu_link', 'created_by', 'updated_by', 'created_at', 'updated_at'
    ];

    protected $primaryKey = 'user_menu_id';
}
krisanalfa
  • 6,268
  • 2
  • 29
  • 38
-1

Eloquent will assume that each table has a primary key column named id. You may define a protected $primaryKey property to override this convention.

class user_menu extends Model
{

    protected $primaryKey = 'user_menu_id';
}
Mahdi Younesi
  • 6,889
  • 2
  • 20
  • 51