oliverbusk
3 months ago

Select model with relationship (limit relationship columns)

Posted 3 months ago by oliverbusk

I have a controller called SelectDocumentsController.php with one method index:

I am trying to return the latest 10 documents, where stream_id equals $stream_id in the URL. I have below AXIOS get:

getDocuments() {
    axios
        .get("/api/editor/stream/" + this.$parent.current.stream_id + "/documents")
        .then(response => {
            this.output = response.data;
        })
        .catch(function (error) {
            console.log(error);
        });
}

In my API file I have below route:

Route::apiResource('editor/stream/{id}/documents', 'Editor\SelectDocumentsController')->only(['index']);

And this is my index method:

public function index($stream_id)
{

    return Stream::with(['documents' => function ($query) {
        $query->select('name');
    }])->findOrFail($stream_id);
    
}

I only want to return the column name from the documents - and I don't really need the columns from the Stream model.

Above index method retuns all columns from Stream, but the documents relationship is empty.

What am I doing wrong?

Please sign in or create an account to participate in this conversation.