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

michael john :

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

Mickael Amar :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=8487&siteId=1