1

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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/

1 Comment

ic...it's strange that if I doing Customer::where('_id', $id)->get(); is not working but Customer::where('_id', 1)->get(); is work, don't know why, is it the same problem?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.