2

I am developing an application using Laravel and AngularJS.

My problem is that I want to get all information from a table for a certain user.

In the routes.php file I have declared a group so that I can reach all comments by going to:

localhost/project/public/api/comments.

I also want to be able to get all comments by a given user by going to:

localhost/project/public/api/comment/id.

Route::group(array('prefix' => 'api'), function() {
    Route::resource('comments', 'CommentController', array('only' => array('index', 'store', 'destroy')));
    Route::get('comment/{id}', function($id) {
       $col = 'user_id';
       return Comments::where($col, '=', $id);
    });
}

When using this code I get the error:

ErrorException
    Object of class Illuminate\Database\Eloquent\Builder could not be converted to string

I can receive the first result by adding:

return Comment::where($col, '=', $id)->first();

But I want to receive all comments for the given user. How can this be done.

2
  • 1
    Did you read the docs? laravel.com/docs/eloquent#basic-usage (hint: ->get()) Commented May 23, 2014 at 9:37
  • I think I missed that part. Thank you, I will read the documentation more thoroughly in the future. Commented May 23, 2014 at 9:52

2 Answers 2

3

You need to get a result

return Comments::where($col, '=', $id)->get();

But you should serialize it to JSON format (for example), so you should do:

$comments = Comments::where($col, '=', $id)->get();
return Response::json(array('success'=>true,'comments'=>$comments->toJson()));
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Almost disappointed I didn't figured out the answer by myself.
1

The Router requires you to return a Response object, not a Collection, a Builder or anything else - since Laravel tries to convert the respons to a string (like it happens to Views), but while Responses have a _toString() method, other objects might not - hence your error.

You should return a View or another response (like JSON), maybe doing something like:

Route::get('comment/{id}', function($id) {
    $comments = Comments::where('user_id', '=', $id)->get();
    return View::make('myview')->with('comments', $comments);
});

2 Comments

I think he most likely will need a JSON response: laravel.com/docs/responses#special-responses
That would be better indeed

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.