【发布时间】:2015-12-18 15:18:20
【问题描述】:
我试图解决我的问题,但我被困在这里无法解决为什么该变量在 home.blade.php 中未定义
这是我的 HomeController.php 我有$items 导致问题的变量
<?php
use app\Item;
namespace App\Http\Controllers;
class HomeController extends BaseController
{
public function __construct(Item $items)
{
$this->items = $items;
}
public function getIndex()
{
$items = Auth::user()->items;
return View::make('home', array(
'items' => $items
));
}
public function postIndex()
{
$id = Input::get('id');
$useId = Auth::user()->id;
$item = Item::findOrFail($id);
if($item->owner_id == $userId)
$item -> mark();
return Redirect::route('home');
}
}
?>
这是 Items 类,我用 eloquent 对其进行了扩展
<?php
class Item extends Eloquent
{
public function mark()
{
$this->done = $this->done?false:true;
$this->save();
}
}
虽然我有另一个 items 函数,但我正试图将其用作变量,因为这是 user.php 的文件,函数在最后定义
<?php
namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Model implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name', 'email', 'password'];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = ['password', 'remember_token'];
public function items()
{
return $this->hasMany('Item','owner_id');
}
}
这是来自视图 home.blade.php 的文件,它在 foreach 循环中给出错误
错误:b5a9f5fc2ee329af8de0b5c94fd30f78 第 7 行中的 ErrorException:
未定义变量:items(查看:C:\Users\Rehman_\Desktop\todo-application\resources\views\home.blade.php)
@extends('master')
@section('content')
<h1>TO DO: Items</h1>
<hr>
<ul>
@foreach ($items as $item)
@endforeach
</ul>
@stop
更新:Route.php 文件
<?php
Route::get('/',array('as'=>'home','uses'=>'PageController@getindex'))->before('auth');
Route::post('/',array('uses','HomeController@postIndex'))->before('csrf');
Route::get('/login',array('as'=>'login','uses' => 'Auth\AuthController@getLogin'))->before('guest');
Route::post('login',array('uses' => 'Auth\AuthController@postLogin'))->before('csrf');
【问题讨论】:
-
在 HomeController 你可以试试
return view('home',compact('items')) -
我已经尝试过 @IE5Master :( 我什至尝试过 view('home')->with('item',$item) 但没有帮助
-
一切似乎都很好。您确定您的路线指向正确的控制器及其方法吗?
-
@Digitlimit 我已经用 route.php 文件更新了代码,你可以看看吗?
-
尝试 Route::get('/', ['middleware'=>'auth', 'as'=>'home','uses'=>'HomeController@getIndex'] );