首先,我是Laravel的新手,我正试图通过添加,修改,删除作者和书籍来制作crud操作示例。所以我的作者crud工作正常,但当我尝试通过获取创建一本书创建的作者我收到此错误:
ErrorException (E_NOTICE)
"Undefined index: firstname"
所以继承我的代码: 我的作者.php
class Authors extends Model
{
protected $table ='authors';
protected $fillable = ['firstname','lastname'];
public function book()
{
return $this->hasMany('Books','author');
}
}
my Books.php:
class Books extends Model
{
protected $table = 'books';
protected $fillable = ['title'];
public function author()
{
return $this->belongsTo('App\Authors');
}
}
我的BooksController.php(它实际上得到了异常):
public function create()
{
return view('books.index');
}
public function store(Request $request)
{
$inputs = $request->all();
$book = new Books();
$book->title = $inputs['title'];
$book->author()->attach($inputs['firstname']);
$book->author()->attach($inputs['lastname']);
$book->save();
return redirect('/books');
}
我的index.php:
@section('content')
<div class="container">
<form method="post" action="{{url('books')}}">
<div class="form-group row">
{{csrf_field()}}
<label for="lgFormGroupInput" class="col-sm-2 col-form-label col-form-label-lg">Title</label>
<div class="col-sm-10">
<input type="text" class="form-control form-control-lg" id="lgFormGroupInput" placeholder="title" name="title">
</div>
</div>
<div class="form-group row">
{{csrf_field()}}
<label for="lgFormGroupInput" class="col-sm-2 col-form-label col-form-label-lg">Author</label>
<div class="col-sm-10">
<select id="author" name="author">
<option value="Z">Select an author</option>
@foreach ($authors as $author)
<option value="{{$author['id']}}">{{$author['firstname']}} {{$author['lastname']}}</option>
@endforeach
</select>
</div>
</div>
<input type="submit" value="Create" />
</form>
</div>
<div class="container">
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Author</th>
</tr>
</thead>
<tbody>
@foreach($books as $book)
<tr>
<td>{{$book['id']}}</td>
<td>{{$book->$author['firstname']}} {{$book->$author['lastname']}}</td>
<td><a href="{{action('BooksController@edit', $book['id'])}}" class="btn btn-warning">Edit</a></td>
<td>
<form action="{{action('BooksController@destroy', $book['id'])}}" method="post">
{{csrf_field()}}
<input name="_method" type="hidden" value="DELETE">
<button class="btn btn-danger" type="submit">Delete</button>
</form>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
@endsection
所以,我不知道为什么我在控制器的商店里得到这个例外......提前谢谢!
答案 0 :(得分:0)
这是因为您的表单中没有任何输入字段。表单必须包含名为firstname
的输入。
您可以通过转储$inputs
字段来检查此问题。例如dd($inputs)
。我确信在您的控制器中,此变量不包含任何名为firstname
的索引,因为您的表单没有任何名为firstname
的输入字段。
答案 1 :(得分:0)
这为我修好了。
composer update