Home » Php » php – Getting wrong data from database even if I am fetching something different in laravel api

php – Getting wrong data from database even if I am fetching something different in laravel api

Posted by: admin February 25, 2020 Leave a comment

Questions:

Hello guys I am working on a laravel project for making api for passing the database value in json format but the problem is I have a users table in this table 2 ids 1 is primary key and second is business _id I want to get data according to business_id but it’s getting data by id please help me how to solve this issue.

Here is my model code

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class user extends Model
{
    protected $table = 'business';

}

Here is my Controller Code

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\user;

class GetController extends Controller
{
    public function databybusinessid($business _id){
    $users = new user();
    $users = user::find($business _id);
    return response()->json($users);
}
}

Thank you so much

How to&Answers:

You are using user::find($business _id)

find() method will automatically search by the primary key but none is defined in your model and Eloquent can’t decide which one to pick from your table. Therefore, you should explicitly set your primary key in your model by adding the following line.

class user extends Model
{
    protected $table = 'business';

    protected $primaryKey = 'business_id';
}

If in doubt, you can also fetch database record by a specific column using where

 $users = user::where('business_id', '=', $business _id)->get()

Laravel documentation about Eloquent ORM
https://laravel.com/docs/5.8/eloquent

Answer:

find() Retrieve a model by its primary key..

So you have to use your code as:

$users = user::where('business_id',$business_id)->first();
// Notice first() Retrieve the first model matching the query constraints...

Or you can change your primary code in model

namespace App;

use Illuminate\Database\Eloquent\Model;

class user extends Model
{
    protected $table = 'business';
    protected $primaryKey = 'business_id';

}

Answer:

find() works only on primary key. you need to use where instead.
or you can define business_id as primary key in your User model.

protected $primaryKey = 'business_id';
public function databybusinessid($business _id){
    $users = new user();
    $users = user::where('business_id',$business _id)->first();
    return response()->json($users);
}