不能使用laravel插入表中

时间:2014-10-16 11:14:21

标签: php laravel laravel-4 eloquent blade

我有这段代码,当我尝试访问laravel.dev/cats/create时会出现一个页面:

Whoops, looks like something went wrong.

这是我的route.php代码(重要部分):

Route::model('cat', 'Cat');

Route::get('cats/create', function() {
    $cat = new Cat;
    return View::make('cats.edit')
        ->with('cat', $cat)
        ->with('method', 'post');
});

Route::post('cats', function(){
    $cat = Cat::create(Input::all());
    return Redirect::to('cats/' . $cat->id)
        ->with('message', 'Successfully created page!');
});
Route::get('cats/{id}', function($id) {
    $cat = Cat::find($id);
    return View::make('cats.single')
        ->with('cat', $cat);
});

这是我的cats / edit.blade.php代码:

@extends('master')
@section('header')
<a href="{{('cats/'.$cat->id.'')}}">&larr; Cancel </a>
    <h2>
    @if($method == 'post')
        Add a new cat
    @elseif($method == 'delete')
        Delete {{$cat->name}}?
    @else
        Edit {{$cat->name}}
    @endif
</h2>
@stop

@section('content')
    {{Form::model($cat, array('method' => $method, 'url'=>
    'cats/'.$cat->id))}}

@unless($method == 'delete')
    <div class="form-group">
        {{Form::label('Name')}}
        {{Form::text('name')}}
    </div>
    <div class="form-group">
        {{Form::label('Date of birth')}}
        {{Form::text('date_of_birth')}}
    </div>
    <div class="form-group">
        {{Form::label('Breed')}}
        {{Form::select('breed_id', $breed_options)}}
    </div>
    {{Form::submit("Save", array("class"=>"btn btn-default"))}}
@else
    {{Form::submit("Delete", array("class"=>"btn btn-default"))}}
@endif
    {{Form::close()}}
@stop

我现在不在问题所在,我有相同的编辑和删除代码,但这些人工作正常,但这一个没有!

这是调试器报告的错误:

Trying to get property of non-object (View: D:\Xampp\htdocs\laravel\app\views\cats\single.blade.php)

<?php echo e($cat->name); ?>

错误提到该行。

感谢您的帮助:))))

修改 这是single.blade.php:

@extends('master')
@section('header')
<?php// dd($cat); ?>
<a href="{{url('/')}}">Back to overview</a>
<h2>
    {{{$cat->name}}}
</h2>
<a href="{{url('cats/'.$cat->id.'/edit')}}">
    <span class="glyphicon glyphicon-edit"></span> Edit
</a>
<a href="{{url('cats/'.$cat->id.'/delete')}}">
    <span class="glyphicon glyphicon-trash"></span> Delete
</a>
Last edited: {{$cat->updated_at}}
@stop
@section('content')
    <p>Date of Birth: {{$cat->date_of_birth}} </p>
    <p>
        @if($cat->breed)
            Breed:
            {{link_to('cats/breeds/' . $cat->breed->name,
            $cat->breed->name)}}
        @endif
    </p>
@stop

我不知道为什么当我去找猫/创建我传递给single.blade.php我认为这是我出错的地方但不知道代码在哪里做

1 个答案:

答案 0 :(得分:0)

问题在于:

Route::get('cats/{id}', function($id) {
    $cat = Cat::find($id);
    return View::make('cats.single')
        ->with('cat', $cat);
});

似乎找不到$id的记录,因此此处$catnull,而且在Blade中不起作用。

您应该检查当前网址是什么($ id值是多少),并确保表中有这样的$ id记录。