【发布时间】:2020-08-22 06:44:05
【问题描述】:
我实际上是 Laravel 的新手,我正在尝试使用这个框架构建一个基本的社交网络。对于这个项目,我创建了一个名为 post 的页面,用户可以在其中添加新帖子。所以我尝试像这样创建posts 表:
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->text('caption');
$table->string('image');
$table->timestamps();
$table->index('user_id');
});
}
在User.php 模型上:
public function posts()
{
return $this->hasMany(Post::class);
}
还有扩展模型的Post.php:
class Post extends Model
{
protected $guarded = [];
Public function user()
{
return $this->belongsTo(User::class);
}
}
而名为PostsController.php 的控制器是这样的:
class PostsController extends Controller
{
public function create()
{
return view('posts.create');
}
public function store()
{
$data = request()->validate([
'caption' => 'required',
'image' => ['required','image'],
]);
auth()->user()->posts()->create($data);
dd(request()->all());
}
}
这是posts文件夹下的create.blade.phpresources目录:
@extends('layouts.app')
@section('content')
<div class="container">
<form action="/p" enctype="multipart/form-data" method="post">
@csrf
<div class="row">
<div class="col-8 offset-2">
<div class="row">
<h1>Add New Post</h1>
</div>
<div class="form-group row">
<label for="caption" class="col-md-4 col-form-label">Post Caption</label>
<input id="caption"
type="text"
class="form-control @error('caption') is-invalid @enderror"
name="caption"
value="{{ old('caption') }}"
autocomplete="caption" autofocus>
@error('caption')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
<div class="row">
<label for="image" class="col-md-4 col-form-label">Post Image</label>
<input type="file" class="form-control-file" id="image" name="image">
@error('image')
<strong>{{ $message }}</strong>
@enderror
</div>
<div class="row pt-4">
<button class="btn btn-primary">Add New Post</button>
</div>
</div>
</div>
</form>
</div>
@endsection
如果你想看看routes.php,这里是:
Auth::routes();
Route::get('/p/create','PostsController@create');
Route::post('/p','PostsController@store');
Route::get('/profile/{user}', 'ProfilesController@index')->name('profile.show');
所以一切看起来都很干净,但问题是每当我尝试上传一些带有标题的虚拟图片时,我都会看到这个错误:
SQLSTATE[HY000]: General error: 1 table posts has no column named caption
但是我尝试在 CMD 上运行 php artisan migrate 语法来检查数据库迁移是否遗漏任何内容,它会输出:Nothing to migrate!
因此,如果您知道为什么会出现此问题或如何解决此问题,请告诉我,我将不胜感激!
提前致谢。
【问题讨论】: