Question

I'm trying to understand the eloquent ORM. I've created a basic post blog.

I want to add post types to my posts, each post should only have one type.

Post types: News Post Video Post Blog Post

Database structure:

Table: archives

id
title
content
created_at
updated_at
excerpt
deleted_at
status

Table: types

id
name
created_at
updated_at

Table: archive_type

id
archive_id
type_id
created_at
updated_at

Models:

Model: Archive

class Archive extends Eloquent
{
    protected $fillable = array('title', 'content', 'excerpt');



    public function type()
    {
        return $this->belongsToMany('Type');
    }

}

Model: Type

class Type extends Eloquent
{

    protected $fillable = array('name');
}

This works, when running:

Archive::with(array('type'))->orderBy('id', 'DESC')->get();

But it returns a collection, I think this is wrong because it should only return one result.

The other problem I have is how to add a new row to the archive_type database for a new post.

Any help is appreciated.

Was it helpful?

Solution

  1. A collection is always returned whether there is zero or 1 million results. The only exception to this rule is the "find" methods, where they are intended for use as a primary key lookup method, in which case, there can only ever be zero or one results, so it will return the model it finds instead of a collection. The behaviour your experiencing with your lookup is as expected.

    If you would like to return the first model, you can place ->first() after your ->get().

  2. To create a new archive type inc. the relation you should do:

    // Get our archive and type models
    $archive = Archive::with(array('type'))->orderBy('id', 'DESC')->get()->first();
    $type = Type::where('name','=','video')->get()->first();

    // attach them!
    $archive->type()->attach($type);

Edit: How to display in blade template.

To pass the collection (or any data for that matter) through to the view you do this in your controller:

return View::make('yourview')->with('archives', $archives);

To loop through a collection in a blade template use @foreach

@foreach ($archives as $archive)
    <p>This is archive id is {{ $archive->id }}</p>
@endforeach

otherwise if you've passed through just one model rather than a collection you can just do

    <p>This is archive id is {{ $archive->id }}</p>

If your going to ask "how do i just show the first model from a collection in the view", the simple answer is, get the model out of the collection first then pass it to your view, anything else would require "business logic" in your view.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top