Return only certain data in from a collection - Laravel

laravel collection
how to get single value from array in laravel
laravel get attribute from collection
laravel get single column value
get single value from collection laravel
laravel custom collection
laravel collection pluck multiple
laravel select only certain columns

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.

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');

    }
}

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

$comments = Comment::where('approved', 1) -> get(['id','name','body']); 

Eloquent Collection, get only certain fields, Eloquent Collection, get only certain fields I have a collection of eloquent objects, and i want to pull only certain fields out of them. the way forward just entails creating the closure for what data i want which is fine, i was just  Forum Laravel Collections get only specific key value. Collections get only specific key value I need an new array with only title from each array. How?

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:

<?php
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.

Collections get only specific key value, Collections get only specific key value Here is my collection (simplified as array​): https://laravel.com/docs/5.3/collections#method-pluck However, if you test to use only() with collection from eloquent results, which contains an array of collections / objects (without key). [ object, object, object ] It will work if the collection contain keys.

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);

Collections - Laravel, Most methods return Illuminate\Database\Eloquent\Collection instances; however, The only method returns all of the models that have the given primary keys: I know this question was originally asked before Laravel 5.0 was released, but as of Laravel 5.0, Collections support the where() method for this purpose. For Laravel 5.0, 5.1, and 5.2, the where() method on the Collection will only do an equals comparison. Also, it does a strict equals comparison (===) by default.

Eloquent: Collections - Laravel, When we get the results from the eloquent, the collection is returned. Laravel Collections are not only limited to eloquent results but can be used When we apply helper methods on eloquent collections, they do not query the database. search method is used to search the collection for a given value. The Illuminate\Support\Collection class provides a fluent, convenient wrapper for working with arrays of data. For example, check out the following code. We'll use the collect helper to create a new collection instance from the array, run the strtoupper function on each element, and then remove all empty elements:

15 Awesome Laravel collection methods, But laravel collection pluck method could have been a good choice to solve this problem. But for now it accepts only string . @milosdakic  Likewise, if a map operation returns a collection that does not contain any Eloquent models, it will be automatically cast to a base collection. Available Methods All Eloquent collections extend the base Laravel collection object; therefore, they inherit all of the powerful methods provided by the base collection class.

How to get couple of fields from collection? · Issue #13667 · laravel , The Collection class in Laravel provides a really nice wrapper for working If the collection contains only strings or numeric values you only have to pass you can pass a parameter to get the maximum value of a certain key. Become a Laravel Partner. Laravel Partners are elite shops providing top-notch Laravel development and consulting. Each of our partners can help you craft a beautiful, well-architected project.

Comments
  • try something $comments = Comment::where('approved', 1)->get(['id','name','body']);
  • Thanks for taking the time to reply. It worked. I completely forgot you could pass arguments into get(). Still fusing the Laravel matrix in my brain.
  • I am glad that I could help, happy coding
  • Thanks for taking the time to reply with a comprehensive solution. I would definitely use this if I was querying more data. For now the answer works well
  • The answer looks good, but I advise you to take a look at transformers, as they help you separate the db structure from your API response.