Bonci Marco
Bonci Marco

Reputation: 301

Get value from view

I have two table User & Article the relationship between tables are

Model:

class Article extends Eloquent {

  public static $table = 'article';

  public function User()
    {
    return $this->has_one('user', 'id');
    }

and

class User extends Eloquent {

  public static $table = 'user';

  public function Article()
    {
       return $this->belongs_to('article', 'id_user');
    }

I want to get name value from User directly on Article view but don't works with error Trying to get property of non-object

My Controller:

public function action_index()
    {

    $Article = Article::order_by('id')->paginate(10);

    return View::make('article.index')->with('$articles', $Article);
    }

My View:

@foreach ($articles->results as $Arti)
      <tr>
       <td>{{$Arti->id}}</td>
       <td>{{$Arti->tag}}</td>
       <td>{{$Arti->user->name }}</td>  <------ ERROR
       <td>{{$Arti->content}}</td>
       <td>{{$Arti->date}}</td>
       <td>

Upvotes: 0

Views: 131

Answers (1)

Phill Sparks
Phill Sparks

Reputation: 20879

Have a look at the below, a few things are different to yours...

  1. Article belongs_to User (not has_one)
  2. User has_many Article (not belongs_to)
  3. Your relationships should be named in lowercase, plural for has_many (i.e. articles or user)
  4. Your relationship subjects should be class names (i.e. Article or User)
  5. Foreign keys should be name relationship_id, i.e. user_id
  6. Add ::with() to your query to eager load relationships
  7. When you paginate you need to access ->results in your view

class Article extends Eloquent {

    // 3: lowercase 'user'
    public function user()
    {
        // 1: Article belongs to User
        // 4: class name 'User'
        // 5: Foreign key on article table is user_id
        return $this->belongs_to('User');
    }

}

// models/user.php

class User extends Eloquent {

    // 3: lowercase plural 'articles'
    public function articles()
    {
        // 2: User has many Articles
        // 4: class name 'Article'
        return $this->has_many('Article');
    }

}

// controllers/articles.php

class Article_Controller extends Base_Controller {

    public $restful = true;

    public function get_index()
    {
        // 6: Eager load the user relationship, ::with('user')
        $articles = Article::with('user')->order_by('id')->paginate(10);
        return View::make('articles.index', compact('articles'));
    }

}

// views/articles/index.blade.php
// 7: access $articles->results from the paginator

@foreach ($articles->results as $article)

    <h1>{{ $article->title }}</h1>
    <p>By {{ $article->user->name }}</p>

@endforeach

{{ $articles->links() }}

Upvotes: 2

Related Questions