Skip to content

Instantly share code, notes, and snippets.

@danielkellyio
Last active May 8, 2020 18:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielkellyio/3c58ca4c4c6c4099f7fa677fd4b41b3c to your computer and use it in GitHub Desktop.
Save danielkellyio/3c58ca4c4c6c4099f7fa677fd4b41b3c to your computer and use it in GitHub Desktop.
Trait to get an empty version of an laravel eloquent model
<?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()
}
*/
@danielkellyio
Copy link
Author

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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment