2018-06-07 22:24
浏览 492

仅返回集合中的某些数据 - Laravel

I'm learning Laravel and have created a public endpoint where I want to output only certain information of some comments if a user is not authenticated from a GET request.

I have managed to filter out the comments based on whether or not they are approved. I now want to filter out the data that is returned. I have attached a screenshot of what is currently returned.

enter image description here

Ideally, I only want to return the id, name and the body in the json. How can I go about this? I tried the pluck() method which did not give the desired results. Any pointers would be greatly appreciated

public function index(Request $request)
    if (Auth::guard('api')->check()) {

        return Comment::all();

    } else {

        $comments = Comment::where('approved', 1)->get();

        return $comments->pluck('id','name','body');


图片转代码服务由CSDN问答提供 功能建议

我正在学习Laravel并创建了一个公共端点,我只想输出某些注释的某些信息。 用户未通过 GET 请求进行身份验证。

我已根据是否获得批准过滤掉了评论。 我现在想要过滤掉返回的数据。 我附上了当前返回的截图。

理想情况下,我只想返回id,name和body JSON。 我怎么能这样做? 我尝试了 pluck()方法,但没有给出所需的结果。 任何指针都将非常感激

 公共函数索引(Request $ request)
 if if(Auth :: guard('api') - > check()  ){
返回注释:: all(); 
} else {
 $ comments = Comment :: where('approved',1) - > get(); 
 返回$ comments-> pluck('id','name','body'); 
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dsc80135 2018-06-07 22:37

    To select the particular columns, you can pass columns name to get as

    $comments = Comment::where('approved', 1) -> get(['id','name','body']); 
    解决 无用
    打赏 举报
  • douxian0008 2018-06-07 22:41

    You can use a transformer to map the incoming data to a sensible output based on the auth state. The following example comes from the Fractal lib:

    use Acme\Model\Book;
    use League\Fractal;
    $books = Book::all();
    $resource = new Fractal\Resource\Collection($books, function(Book $book) {
        return [
            'id'      => (int) $book->id,
            'title'   => $book->title,
            'year'    => $book->yr,
            'author'  => [
                'name'  => $book->author_name,
                'email' => $book->author_email,
            'links'   => [
                    'rel' => 'self',
                    'uri' => '/books/'.$book->id,

    Ideally, you would create 2 classes that extend from Transformer and pass the correct one to the output.

    解决 无用
    打赏 举报
  • doubei2340 2018-06-08 07:02

    If you want to pass the result as json respose

    $comments = Comment::where('approved', 1)->pluck('id','name','body')->toArray();

    return Response::json($comments);

    If you want to pass the result as to blade

    $comments = Comment::where('approved', 1)->pluck('id','name','body')->toArray();

    return view('your_blade_name')->with('comments',$comments);

    解决 无用
    打赏 举报

相关推荐 更多相似问题