Siu San
Siu San

Reputation: 11

Jenssegers Laravel-Mongodb return null if get by parameter

I'm new to Laravel-Mongodb, trying to get result by parameter but it's not working

Model:

use Jenssegers\Mongodb\Model as Eloquent;

class Customer extends Eloquent {
    protected $connection = 'mongodb';
    protected $collection = 'Customer';
}

Controller:

class AdminController extends Controller
{
    public function index() {
        return Customer::all();
    }

    public function show($id) {
        return Customer::find($id);
    }
}

It's alright for index() but it will return empty for show($id), it will work if using:

return Customer::find(1);

I'm not sure why it's not working with parameter, am I missing something?

Upvotes: 1

Views: 2494

Answers (2)

Harsh Virani
Harsh Virani

Reputation: 355

You need to add one protected variable in your model like below

protected $primaryKey = “customerId”

You can add your own primary key to this variable but if you won’t add this line in model, model will by default take _id as your primary key and _id is autogenerated mongodb’s unique id.

Thats the reason why you are not able to get record by id.

Upvotes: 1

tommy
tommy

Reputation: 3625

1 is not a valid ObjectId. Try to find a valid ID with a tool like Robomongo or just list your customers with your index method to find out what the IDs are.

The query should look more like this:

return Customer::find("507f1f77bcf86cd799439011");

You can read more about MongoDBs ObjectId here:

https://docs.mongodb.org/manual/reference/object-id/

Upvotes: 0

Related Questions