一、下载 laravel 5.4
composer create-project laravel/laravel=5.4.* laravel5.4_event
新建数据库 laravel5.4_event
修改 .evn 配置文件
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel5.4_event
DB_USERNAME=laravel5.4_event
DB_PASSWORD=laravel5.4_event
修改中国时区,在 config/app.php 中修改
'timezone' => 'PRC',
切换目录
cd laravel5.4_event
二、创建模型
创建 post model
php artisan make:model Post -m
修改迁移文件:posts_table.php
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('content');
$table->timestamps();
});
}
执行数据迁移
php artisan migrate
如果报错
Specified key was too long; max key length is 1000 bytes
问题解决:在 AppServiceProvider 中调用 Schema::defaultStringLength 方法来实现配置:
use Illuminate\Support\Facades\Schema;
public function boot()
{
Schema::defaultStringLength(191);
}
启动服务
php artisan serve
三、模型事件
修改 app/Post.php
protected $fillable = [
'title', 'content'
];
修改 routes/web.php
Route::get('/', function () {
\App\Post::create([
'title' => 'Title',
'content' => 'Content',
]);
});
在 laravel 5.4 之前,监听文章创建的写法:在 routes/web.php 新增代码
Event::listen('eloquent.created: App\Post', function(){
dd('A post was created');
});
laravel 5.4 的写法
修改 app/Provides/EventServiceProvider.php
protected $listen = [
'App\Events\PostWasPublished' => [
'App\Listeners\PostWasPublishedListener',
],
];
执行命令
php artisan event:generate
此命令会新增两个文件:app/Events/PostWasPublished.php、app/Listeners/PostWasPublishedListener.php
修改 app/Post.php
use App\Events\PostWasPublished;
protected $events = [
'created' => PostWasPublished::class,
];
修改 app/Events/PostWasPublished.php
public $post;
public function __construct($post)
{
$this->post = $post;
}
修改 app/Listeners/PostWasPublishedListener.php
public function handle(PostWasPublished $event)
{
dd($event->post->toArray());
}
可以使用
$event->post->title
获取标题