Last active
May 8, 2020 18:03
-
-
Save danielkellyio/3c58ca4c4c6c4099f7fa677fd4b41b3c to your computer and use it in GitHub Desktop.
Trait to get an empty version of an laravel eloquent model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Illuminate\Support\Facades\Schema; | |
/** | |
* Trait WithEmptyRecord | |
* Use to get an empty version of an eloquent model | |
* (contains all the column names with empty values (or default values specified by the $attributes array) ) | |
*/ | |
trait WithEmptyRecord{ | |
public static function emptyRecord(){ | |
$model = new self; | |
collect(Schema::getColumnListing($model->table)) | |
->flip() | |
->each(function($item, $key) use ($model){ | |
$default = $model->attributes[$key] ?? ''; | |
$model[$key] = old($key, $default); | |
}); | |
return $model; | |
} | |
} | |
/** | |
* Example: | |
// app/Models/Post.php | |
class Post extends Model{ | |
use WithEmptyRecord | |
} | |
// app/Http/Controllers/PostsController.php | |
public function create(){ | |
$post = Post::emptyRecord() | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
found this super helpful to reuse forms for both create and update (can just pass $post->name, whatever as the value into the input and for create it won't error out, it'll just be an empty or the default value)