0

When I use the following code in my routes/web.php file, I keep getting the error of 'Trying to get property of non-object' each time I visit the /user/{id}/post url.

routes/web.php

use App\Post;
use App\User;

Route::get('/user/{id}/post', function($id) {
  return User::find($id)->name;
});

App/User.php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function posts() {
        return $this->hasOne('Post');
    }
}

App/Post.php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model
{
    // protected $table = 'posts';

  use SoftDeletes;

  protected $dates = ['deleted_at'];
  protected $fillable = [''];
}

How do I view data stored in the table users? I put some dummy data in there to try and retrieve it.

1 Answer 1

1

If user hasOne relation with Post,it is better to make relation post() rather than posts() and post belongsTo user.

User Model:

public function post() {
    return $this->hasOne('App\Post');
}

Post Model:

 public function user()
    {
        return $this->belongsTo('App\User'); 
    }

then, this gives all user's post along with user name.

$users=User::with('post')->get();
foreach($users as $user)
{
  print_r($user->name);
  print_r($user->post);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.