创建主题时我无法获得category_id。这是我的代码和mysql。我想我在论坛控制器上存储方法有问题。
主题创建页面
@extends('app')
@section('content')
<h1>トピック</h1>
<hr>
{!! Form::open(['url' => 'forums']) !!}
<div class="form-group">
{!! Form::label('title', 'タイトル:') !!}
{!! Form::text('title', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('body', '本文:') !!}
{!! Form::textarea('body', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('category', 'カテゴリー:') !!}
{!! Form::select('category', $categories,null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::submit('送信',['class' => 'btn btn-primary form-control']) !!}
</div>
{!! Form::close() !!}
@stop
论坛控制器
<?php
namespace App\Http\Controllers;
use App\Category;
use App\User;
use App\Http\Controllers\Controller;
use App\Http\Requests;
use App\Topic;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class ForumsController extends Controller
{
public function index()
{
$categories = Category::all();
$topics = Topic::latest()->get();
return view('forums.index',compact('categories','topics'));
}
public function create()
{
$categories = Category::lists('title', 'id');
return view('forums.create', compact('categories'));
}
public function store(Request $request)
{
Auth::user()->topics()->save(new Topic($request->all()));
// flash()->success('投稿しました','success');
// return redirect('forums');
}
}
类别模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $fillable = [
'title'
];
public function topics()
{
return $this->hasMany('App\Topic');
}
}
主题模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class topic extends Model
{
protected $fillable = [
'title',
'body'
];
public function category()
{
return $this->belongsTo('App\category');
}
public function user()
{
return $this->belongsTo('App\User');
}
}
答案 0 :(得分:0)
将category_id添加到主题的模型可填充数组中,如下所示
protected $fillable = [
'title',
'body',
'category_id'
];