Laravel-Livewire笔记系列(五)-Livewire留言列表展示-1
作者:温新
时间:2021-08-14
hi,我是温新,一名PHPer
1)本系列笔记使用Laravel8.x作为演示;
2)使用Livewire2.x版本
通过此案例可以体会到livewire
的强大,感觉什么都做,数据就已经出来,但好像什么都做了。
准备工作
1)生成数据表
2)删除StudyList
组件与模板
php artisan livewire:delete StudyList
// 输入yes
第一步:创建留言模型及数据表
1)创建模型及迁移文件
php artisan make:model LeaveMsg -m
2)编写迁移文件
public function up()
{
Schema::create('leave_msgs', function (Blueprint $table) {
$table->id();
$table->unsignedInteger('user_id')->index()->comment('发布者');
$table->text('content')->comment('留言内容');
$table->timestamps();
});
}
3)执行迁移文件
php artisan migrate
请自行填充相关数据
第二步:创建组件
// 留言列表组件
php artisan livewire:make LeaveMsgIndex
第三步:定义模型关联方法
// App\Models\LeaveMsg.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class LeaveMsg extends Model
{
use HasFactory;
protected $guarded = [];
public function user()
{
return $this->belongsTo(User::class,'user_id','id');
}
}
// App\Models\User.php
public function leageMsg()
{
return $this->hasMany(LeaveMsg::class,'user_id','id');
}
第四步:编写留言列表组件
// app/Http/Livewire/LeaveMsgIndex.php
<?php
namespace App\Http\Livewire;
use App\Models\LeaveMsg;
use Livewire\Component;
// 留言列表组件
class LeaveMsgIndex extends Component
{
public function render()
{
$leaveMsgs = LeaveMsg::all();
return view('livewire.leave-msg-index', compact('leaveMsgs'));
}
}
第五步:编写留言列表组件模板
// resources/views/livewire/leave-msg-index.blade.php
<div>
<ul>
@foreach($leaveMsgs as $v)
<li>{{$v->user->name}}--{{ $v->content }}</li>
@endforeach
</ul>
</div>
第六步:路由访问
路由-控制器-视图是使用之前文章所创建的,这里就不再重复记录了。
我是温新
每天进步一点点,就一点
请登录后再评论