NewsController.php
这是控制器,我使用create函数将记录添加到数据库中,但是当我添加所有记录时,记录将为空
public function insertNews() {
$attribute = [
'Ntitle' => 'News Title',
'Ndesc' => 'News Description',
'Naddedby' => 'News Added By',
'Ncontent' => 'News Content',
'Nstatus' => 'News Status'
];
$data = $this->validate(request(), [
'Ntitle' => 'required',
'Ndesc' => 'required',
'Naddedby' => 'required',
'Ncontent' => 'required',
'Nstatus' => 'required'
], [], $attribute);
News::create($data);
return redirect('all/news');
}
我使用dd()显示记录,它将与令牌和所有其他值一起显示
dd(request()->all())
News.php 这是模型文件
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class News extends Model
{
use SoftDeletes;
protected $primaryKey = 'News_ID';
protected $date = ['delete_at'];
protected $fillable = ['News_Title', 'News_Descrption', 'News_Content', 'Added_By', 'News_Status'];
}
web.php 这是网络文件(路线)
Route::post('insert/news', 'NewsController@insertNews');
news.blade.php
这是刀片文件,其中包含我发送给控制器的表格
<form action="{{ url('insert/news') }}" method="POST">
{{ csrf_field() }}
<input type="text" name="Ntitle" value="{{ old('Ntitle') }}" placeholder="News Title"><br />
<input type="text" name="Ndesc" value="{{ old('Ndesc') }}" placeholder="News Descrption"><br />
<input type="number" name="Naddedby" value="{{ old('Naddedby') }}" placeholder="News Added By"><br />
<textarea name="Ncontent" value="{{ old('Ncontent') }}" placeholder="News Content"></textarea><br />
<select name="Nstatus">
<option value="Active" {{ old('Nstatus') == 'Active' ? 'selected' : '' }}>Active</option>
<option value="Pending" {{ old('Nstatus') == 'Pending' ? 'selected' : '' }}>Pending</option>
<option value="Disabled" {{ old('Nstatus') == 'Disabled' ? 'selected' : '' }}>Disabled</option>
</select><br />
<input type="submit" value="Add News">
</form>
答案 0 :(得分:1)
代码无法正常运行的原因有很多:
public function insertNews() {
$attribute = [
'Ntitle' => 'News Title',
'Ndesc' => 'News Description',
'Naddedby' => 'News Added By',
'Ncontent' => 'News Content',
'Nstatus' => 'News Status'
];
$this->validate(request(), [
'Ntitle' => 'required',
'Ndesc' => 'required',
'Naddedby' => 'required',
'Ncontent' => 'required',
'Nstatus' => 'required'
], [], $attribute);
News::create($attribute);
return redirect('all/news');
}
确保已将所有字段添加到受保护的$ fillable = [];在您的模型中是这样的:
class News extends Model {
protected $fillable = [
'Ntitle', 'Ndesc', 'Naddedby', 'Ncontent', 'Nstatus'
];
答案 1 :(得分:0)
您需要将值传递给create()方法。
//Passing the request to create method
News::create($request->all());
return redirect('all/news');
如果您在“新闻”模型的$ fillable变量中添加了输入名称,它将立即存储。
//News.php (Model)
protected $fillable = ['Ntitle', 'Ndesc', 'Naddedby', 'Ncontent', 'Nstatus'];
我更喜欢使用
//News.php (Model)
protected $guarded = [];
答案 2 :(得分:0)
可以给我我的网络路线吗? 所以我可以告诉你这是怎么回事,
我认为您的路线应该
Route::namespace('your_Controller_Foldername')->group(function () {
Route::resource('insert/news', 'NewsController');
});