سؤال

I'm very new to Laravel and I am trying to access an object I get successfully back from the database. Its a

book

object and when I print it to screen with this line:

{{{ $book or 'Default' }}}

I get back the object printed as so:

[{"id":"1","title":"Dress yourself like the Crabmeister","isbn":"18274827","publication_date":"14\/03\/1978","author_id":"1","genre_id":"4","available":"1","created_at":"1397346572","updated_at":"1397346572"}]

Although this is fine and proves successful, when i try to access just one attribute such as

title

, it gives me an undefined exception. I try to access it with this line:

$book->title

I'm sure its an obvious answer but any help appreciated, thanks.

هل كانت مفيدة؟

المحلول

It depends on how you return your object. There are multiple ways with Laravel. Your returned Object seems to be a JSON-object.

Try the following in your view

<script>
    var book = '{{ $book }}';
    //...

window.console.log(book.title);
</script>

Or you don't return the book object as JSON and you access it in the view like this:

@foreach($book as $b)
    {{ $b->title }}
@endforeach

Edit after comment

Try to put the get() method at the end of your model's call (Just an example as I don't see your model):

$books = new Book();
return $books->where('something', '=', 'some other')->get();

Also, in your model, you can do

...->get()->toJson();
...->get()->toArray();

Laravel Docs:

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top