nova-drafts
nova-drafts copied to clipboard
[BUG] - Unable to determine programatically if a Model type is a draft in an observer
Describe the bug
I am attempting to use a Laravel Observer to perform an action on the Creating
and/or Created
step of a models lifecycle. In this created()
method, I am trying to determine if the model has been saved as a draft, or created fully (i.e. published), and perform a different action based on this.
I seem to be unable to do this, as the $model->published
property is always $false
and other properties like $model->draft
or $model->draft_parent_id
aren't populated at these stages. Published being $false
certainty makes sense in creating()
, but surely not in created()
? I have also tried saved()
for good measure - but it was also false there.
It seems the published flag is only set after all other stages have completed somehow, and I am not sure of the mechanism through which it does this - as I can't tell when the /draft-publish
endpoints are called for the DraftController
to set published to $true
.
To Reproduce
Steps to reproduce the behavior:
- Create an observer for a pre-existing model you have, mine was
Report
:
php artisan make:observer ReportObserver --model=Report
- Implement an Observer lifecycle stage (i.e. saving/creating/created/saved):
namespace App\Observers;
use App\Report;
use Illuminate\Support\Facades\Log;
class ReportObserver
{
public function created(Report $report){
Log::info($report);
Log::info($report->published); // This always returns false
Log::info($report->draft); // This is always null
Log::info($report->draft_parent_id); // This is always null
}
}
Expected behavior
There should be a mechanism made available to determine if a model object is a unpublished / published item (i.e. draft) in an Observer.
Screenshots
Environment(please complete the following information):
- PHP version: [7.4 & 8.0]
- Laravel Nova Version [3.29.0]
- Version [1.1.4]
Additional context
N/A
Is this bug potentially related to another currently open bug ? https://github.com/optimistdigital/nova-drafts/issues/1
Hei! 👋🏻
Pull requests are welcome. This is most likely caused by us not calling $data->save();
after changing published state.
https://github.com/optimistdigital/nova-drafts/blob/master/src/Models/Draft.php#L32
I currently don't have a test project with drafts set up, so if you could verify that adding save()
there it fixes the issue, i can do a new release.
Also, since i'm using the replicate() function, not sure whether laravel calls the created function alongside with it. https://github.com/optimistdigital/nova-drafts/blob/master/src/Models/Draft.php#L23
@KasparRosin do you think this has to do with the touch property? https://laravel.com/docs/9.x/eloquent-relationships#touching-parent-timestamps