C
C
Crash XD2019-03-26 08:29:24
API
Crash XD, 2019-03-26 08:29:24

How to hide fields when displaying in a collection in Laravel API Resources?

There is, for example, a route for displaying a list of articles and a route for displaying a specific article:

public function index()
{
    return new ArticleCollection(Article::all());
}

public function show(Article $article)
{
    return new ArticleResource($article);
}

In ArticleResource:
public function toArray($request)
{
    return [
        'id' => $this->id,
        'title' => $this->title,
        'content' => $this->content,
    ];
}

In ArticleCollection:
public function toArray($request)
{
    return [
        ArticleResource::collection($this->collection),
    ];
}

Is it possible to make it so that when listing articles does not display the content field, without creating another additional ArticleResource separately for listing?
Those. Roughly speaking, for the first route, get json:
{
    "data": [
        {
            "id": 1,
            "title": "Заголовок 1"
        },
        {
            "id": 2,
            "title": "Заголовок 2"
        }
    ]
}

For the second route, get:
{
    "data": {
        "id": 1,
        "title": "Заголовок 1",
        "content": "Lorem Ipsum is simply dummy text of the printing and typesetting industry.",
    }
}

Maybe through $this->when somehow check that this is a resource inside the collection or something like that?

Answer the question

In order to leave comments, you need to log in

5 answer(s)
C
Crash XD, 2019-03-26
@crashxd

Found this solution . Maybe not super convenient, but solves my problem.

N
NubasLol, 2019-03-26
@NubasLol

public function toArray($request)
    {
        return $this->collection
            ->map
            ->toArray($request, true)
            ->all();
    }

public function toArray($request, $isCollection = false)

A
Alexey Shmyrko, 2019-03-30
@shmyrkoalejsejj

Why don't you specify only what you need in select(id, title), why pull out everything from the database to hide it later?

R
riot26, 2016-12-24
@riot26

From the picture it is not clear what parallax affects. Angle of inclination?
And according to the subject: after with gradient/borders or svg

L
lacrim, 2016-12-24
@lacrim

You can skew the block with CSS transform:;
Parallax or the simplest - background-position:fixed;
Or hang a js scroll to change the angle of the transform property
There is also an interesting parallax library with a lot of features - markdalgleish.com/projects/stellar.js

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question