Home > database >  Primary Key is different from the default id that laravel searches for
Primary Key is different from the default id that laravel searches for

Time:12-09

I have added a custom primary key within the table and now the Laravel is not even finding the result at all. giving error that the page could not be found.

NotFoundHttpException

No query results for model [App\usersinformation].

Controller --------------------

public function show(usersinformation $usersinformation)
{
    //
  //  $users =  $user = usersinformation::where('user-id','=',$usersinformation) -> first();
    
        return view('usersinformation.show');

}

Model -------------------

class usersinformation extends Model
{
    //

    public $table = "usersinformation";
    public $incrementing = false;
    
    protected $fillable = [

        'fname','lname', 'user-picture', 'phone-number', 'user-id', 'place-id'

    ];
    protected $primaryKey = 'user-info-id';

    public function users(){
        $this -> belongsTo('App\users');
    }

route ---- web.php

Route::post('/show','App\Http\Controllers\usersinformationController@show');

Still facing the same issue, if I comment the primary key, it will give error that the id field is not found within the table when I add the custom primary key in the model, it will give error page not found.

CodePudding user response:

You're typehinting usersinformation $usersinformation, so it's trying to find the record for the ID you're passing in. In the next line, you're trying to pass the id into the user-id, so I'm guessing you're actually passing in the user-id to the route, and not the id of the user information row. If that is the case, then you need to change the typehinting so it won't try to find the record before it enters the function.

public function show($user_id)
{
  $user_information = usersinformation::where('user-id','=',$user_id) -> first();
    
  return view('usersinformation.show', ['userinformation' => $user_information]);

}

Your primaryKey line is fine and should work, but know that dashes in table and column names are strongly discouraged because it leads to all sorts of confusion. Underscores are much better. See this link for more information.

  • Related