我尝试从数据库中读取错误消息
未定义变量:联系人(视图:C:\ Users \ My-Asus \ contact_manager \ resources \ views \ contacts \ index.blade.php)
错误是指下面index.blade.php中每个循环使用的变量$ contacts
@extends('layouts.main')
@section('content')
<div class="panel panel-default">
<table class="table">
@foreach ($contacts as $contact)
<tr>
<td class="middle">
<div class="media">
<div class="media-left">
<a href="#">
<img class="media-object" src="http://placehold.it/100x100" alt="...">
</a>
</div>
<div class="media-body">
<h4 class="media-heading">{{ $contact->name }}</h4>
<address>
<strong>{{ $contact->company }}</strong><br>
{{ $contact->email }}
</address>
</div>
</div>
</td>
<td width="100" class="middle">
<div>
{!! Form::open(['route' => ['contacts.destroy', $contact->id], 'method' => 'DELETE']) !!}
<a href="{{ route('contacts.edit', ['id' => $contact->id]) }}" class="btn btn-circle btn-default btn-xs" title="Edit">
<i class="glyphicon glyphicon-edit"></i>
</a>
<button class="btn btn-circle btn-danger btn-xs" title="Delete" onclick="return confirm('Are You sure ?')">
<i class="glyphicon glyphicon-remove"></i>
</button>
{!! Form::close() !!}
</div>
</td>
</tr>
@endforeach
</table>
</div>
<div class="text-center">
<nav>
{!! $contacts->appends( Request::query() )->render() !!}
</nav>
</div>
@endsection
我已经创建了这样的控制器,这有什么问题吗?
class ContactsController extends Controller
{
public function index(){
$contacts = Contact::all();
return view('contacts.index', compact('contacts'));
}
}
这是路由(routes / web.php)
Route::get('/', function () {
return view('contacts.index');
});
Route::resource('contacts', 'ContactsController');
非常感谢您的帮助!
答案 0 :(得分:1)
您将直接在视图页面中返回“ /”。因此,这就是为什么它没有从控制器获取通讯录变量的原因。
在您的web.php文件中,
Route::get('/', 'ContactController@index')->name('/');
现在尝试使用
清除缓存和路由php artisan config:cache
php artisan route:clear
让我知道您是否仍然面临该问题
OR
直接在路线中调用此
Route::get('/', function () {
$contacts = \App\Contact::all();
return view('contacts.index',compact('contacts'));
});
答案 1 :(得分:1)
在route.php
文件中,您正在调用view('contacts.index')
,但没有contacts
的{{1}}数据。
compact
但是当您调用Route::get('/', function () {
return view('contacts.index');
});
时,资源将调用索引方法。
/contacts
因此,您的代码将与Route::resource('contacts', 'ContactsController');
一起使用,如果要使用相同的/contacts
网址,则必须在路由文件中使用'/'
,如下所示。
compact('contacts')
答案 2 :(得分:0)
我认为您直接通过路由调用了"index.blade.php"
。您必须调用方法"ContactsController"
的索引。
删除您的路由代码,并在路由文件中使用以下代码:
Route::get('/', 'ContactsController@index');