Laravel Varbox get drafted items programatically

Viewed 74

I've created a draftable custom entity. I noticed that from the admin I can save it as a draft or publish it.

However, I'm wondering how can I fetch all my drafted or published records and how can I determine if a single record instance is drafted or published?

Thank you!

1 Answers

Given what you've said, I'm assuming you're already using the Varbox\Traits\IsDraftable trait on your model.

You can make use of the query scopes that trait exposes in order to only fetch your drafted or published records like so:

$onlyPublishedRecords = YourModel::withoutDrafts()->get();

$onlyDraftedRecords = YourModel::onlyDrafts()->get();

Here's the documentation part for reference: https://varbox.io/docs/1.x/draft-records#query-scope


To answer your second part of the question, you can check if a record is drafted or published by using the isDrafted method:

$model = YourModel::find($id);

dump($model->isDrafted()); // true or false

Here's the documentation part for reference: https://varbox.io/docs/1.x/draft-records#check-if-draft

Related