PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, March 1, 2022

[FIXED] Primary Key is different from the default id that laravel searches for

 March 01, 2022     ajax, laravel, laravel-5, php     No comments   

Issue

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.


Solution

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.



Answered By - aynber
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing