Laravel 4 - 试图获得非对象的属性

时间:2014-01-04 17:02:37

标签: php laravel laravel-4

我一直在使用Laravel 4.1创建一个包含用户关系的图书清单应用。我有用户关系工作但是当我添加分页时,我得到以下错误异常:

ErrorException
Trying to get property of non-object (View: /app/views/books/index.blade.php)

return link_to_route('user.books.show', $book->title, [$book->user->username, $book->id]);

错误从视图(book / index.blade.php)生成,但错误异常实际上来自帮助程序(参见下文)。

Helpers.php - Line 11 generates the error

控制器 - PARTIAL

public function show($id)
{
    $book = Book::findOrFail($id);

    return View::make('books.show', compact('book'));
}
}

我的路线档案

设置为强制该地址为USERNAME> BOOKS> BOOK_ID:

#Books Controller

Route::resource('books', 'BooksController');

Route::get('books/{id}', 'BooksController@show')->where('id', '\d+');

//Books ID Rerouting  - USERNAME -> BOOK -> Book ID

Route::get('{username}/books', 'UserBooksController@index');

Route::get('{username}/books/{id}', ['as' => 'user.books.show', 'uses' => 'UserBooksController@show']);

我收到错误的地方 - 它不再识别

user.books.show

books / index.blade.php文件

    @foreach(array_chunk($books->getCollection()->all(), 3) as $row)    

    <div class="row">

    @foreach ($row as $book)

      <div class="col-md-4">
        <div class="thumbnail">
         <img data-src="{{ $book->image }}" alt="">
          <div class="caption">
            <h3>{{ link_to_book($book) }}</h3>
            <p>{{ $book->synopsis }} </p>
            <p><a href="{{ link_to_book($book) }}" class="btn btn-primary" role="button">Buy Now</a></p>
          </div>
        </div>
      </div>

    @endforeach
      </div>
    </div>
@endforeach     

{{ dd(Request::only('1')) }}    

{{ $books->appends(Request::only('1'))->links() }}  

HELPER FILE

<?php


function link_to_book(Book $book)

{
    return link_to_route('user.books.show', $book->title, [$book->user->username, $book->id]);
}

2 个答案:

答案 0 :(得分:21)

我有同样的问题,这就是我如何解决它。要访问数组中的元素,请使用数组表示法:$book['image']

$book->image是对象表示法,只能用于访问对象属性和方法。 试试这个:

 @foreach(array_chunk($books->getCollection()->all(), 3) as $row)    

    <div class="row">

    @foreach ($row as $book)

      <div class="col-md-4">
        <div class="thumbnail">
         <img data-src="{{ $book['image'] }}" alt="">
          <div class="caption">
            <h3>{{ link_to_book($book) }}</h3>
            <p>{{ $book['synopsis'] }} </p>
            <p><a href="{{ link_to_book($book) }}" class="btn btn-primary" role="button">Buy Now</a></p>
          </div>
        </div>
      </div>

    @endforeach
      </div>
    </div>
@endforeach     

{{ dd(Request::only('1')) }}    

{{ $books->appends(Request::only('1'))->links() }}  

那应该解决它。它的含义是你以一种只应该用于对象的方式调用非对象。如果有效,请告诉我。

答案 1 :(得分:7)

如果在任何点上都为null,请尝试输出gettype($ book)

{{$book['image']}} //will not complain about it but gives output ""
{{$book->image}} //will complain about it and throws an exception

我认为这就是原因

我正在使用laravel5,但我认为它与laravel4相同