- 
          
 - 
                Notifications
    
You must be signed in to change notification settings  - Fork 20
 
Keepable model
        Pe Ell edited this page Apr 17, 2017 
        ·
        3 revisions
      
    Keep functionality required when you are trying to attach related models before parent one isn't persisted in application.
Issue:
- User press 
Create Postbutton. - Create post form has image uploader.
 - On image uploading user can't attach image to post before post entity wouldn't been stored in database.
 
Solution:
- Add 
HasKeptFlagtrait to model (and add booleanis_keptcolumn to model's database table). - Create empty model on form loading (it will has 
is_kept = 0by default). - Feel free to add any relations to the model.
 - Model will be marked as required to be kept as soon as model will be saved\updated for the first time after creation.
 
Known limitations:
- Using this methodology you wouldn't have create form, only edit will be available.
 - Not all the models allows to have empty attributes on save. Such attributes could be set as nullable to allow create blank model.
 - To prevent spam of unkept models in database they could be deleted on a predetermined schedule (once a week for example).
 
<?php
namespace App\Models;
use Cog\Flag\Traits\Classic\HasKeptFlag;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
    use HasKeptFlag;
}Your model is now can be marked to be kept!
Model must have boolean is_kept column in database table.
By default all records that have a is_kept equals to 0 will be excluded from your query results. To include unkept records, all you need to do is call the withUnkept() method on your query.
Post::all();
Post::withoutUnkept();Post::onlyUnkept();Post::withUnkept();Post::where('id', 4)->keep();Post::where('id', 4)->unkeep();Post::onlyUnkeptOlderThanHours(4);Output will have all unkept models created earlier than 4 hours ago.