0

i'm building Restful API Using Laravel

what i wanna to do is to get specific columns in JSON response instead on get all column

For example I've Product Table with these columns

title - price - description - status - created_at - updated at

and i just want to show title, price and description in JSON Response

So, any idea to do that?

3
  • 3
    Post your query code Commented Jun 25, 2020 at 17:58
  • 3
    There's many ways to do this and which one you should use depends on your specific requirements. For example you could use resources Commented Jun 25, 2020 at 18:02
  • I support the notion of resources, since you are building an API resources are standard Commented Sep 12, 2022 at 8:45

3 Answers 3

3

You can use select for certain field display :

Model::select('title', 'price', 'description')->get();

Or, in get() method :

Model::get(['title', 'price', 'description']);

As you would like to make some typically visible attributes hidden on a given model instance, you may use the makeHidden method :

$data = Model::all();
$data->makeHidden('price');

Now price will be hidden from your query.

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

3 Comments

You can also return Model::select ('field')->get() and Laravel will return json
is this way source?
0

You can use map function after get() or all() method.

EX:

Model::all()->map(function($product) {
    return [
        'title',
        'price',
        'description'
    ];
});

Comments

0

You can use a map only function which will give you the benefit that it also handles computed fields and not only "physical" SQL fields:

Model::get()->map->only([
      'title',
      'price',
      'description'
]);

The Answer from Abu Bin Oalid above does not work, it gives you just the attributes, and not the actual values.

Comments

Your Answer

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