Skip to content

Instantly share code, notes, and snippets.

@oliuz
Forked from ryangjchandler/PostModelEvents.php
Created March 29, 2021 12:03
Show Gist options
  • Select an option

  • Save oliuz/56029c4280dca4d4499a263895da07ae to your computer and use it in GitHub Desktop.

Select an option

Save oliuz/56029c4280dca4d4499a263895da07ae to your computer and use it in GitHub Desktop.
<?php
protected $hidden = ['published_at'];
static::creating(function (Post $post) {
$post->visible('published_at');
Validator::validate($post->toArray(), static::$rules);
});
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
class Post extends Model
{
public static function boot()
{
parent::boot();
static::creating(function (Post $post) {
if (! $post->slug) {
$post->slug = Str::slug($post->title);
}
});
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Validator;
class Post extends Model
{
public static $rules = [
'title' => 'required|string|max:255',
'slug' => 'required|string',
'excerpt' => 'nullable|string|max:160',
'published_at' => 'nullable|date',
];
public static function boot()
{
parent::boot();
static::creating(function (Post $post) {
Validator::validate($post->toArray(), static::$rules);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment