一、创建模型
创建私信模型
php artisan make:model Message -m
修改生成的 database/migrations/create_messages_table.php
public function up()
{
Schema::create('messages', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('from_user_id');
$table->unsignedInteger('to_user_id');
$table->text('content');
$table->string('has_read',8)->default('F');
$table->timestamp('read_at')->nullable();
$table->timestamps();
});
}
执行数据迁移
php artisan migrate
修改 app/Message.php
protected $table = 'message';
protected $fillable = ['from_user_id','to_user_id','content'];
public function fromUser()
{
return $this->belongsTo(User::class,'from_user_id');
}
public function toUser()
{
return $this->belongsTo(User::class,'to_user_id');
}
修改 app/User.php
public function messages()
{
return $this->hasMany(Message::class,'to_user_id');
}
二、创建控制器
创建私信控制器
php artisan make:controller MessagesController
修改 routes/api.php
Route::post('/message/store', 'MessagesController@store')->middleware('auth:api');
新建文件:app/Repositories/MessageRepository.php
namespace App\Repositories;
use App\Message;
class MessageRepository
{
public function create(array $attributes)
{
return Message::create($attributes);
}
}
修改生成的控制器:app/Http/Controllers/MessagesController.php
namespace App\Http\Controllers;
use Auth;
use App\Repositories\MessageRepository;
class MessagesController extends Controller
{
protected $messageRepository;
public function __construct(MessageRepository $messageRepository)
{
$this->messageRepository = $messageRepository;
}
public function store()
{
$message = $this->messageRepository->create([
'to_user_id' => request('user'),
'from_user_id' => user('api')->id,
'content' => request('content')
]);
if($message){
$status = true;
}else{
$status = false;
}
return response()->json(['status'=>$status]);
}
}
三、创建视图
新建 resources/assets/js/components/SendMessage.vue
注册组件:修改 resources/assets/js/app.js
Vue.component('send-message', require('./components/SendMessage.vue'));
执行 gulp
gulp
修改 resources/views/questions/show.blade.php
访问:http://127.0.0.1:8000/questions/id,id 为问题 ID
点击按钮进行测试