<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* 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',
];
// create a public function to return ONE post
public function post() {
return $this->hasOne('App\Post'); // looks for 'user_id' by default
// return $this->hasOne('App\Post', 'the_user_id'); // write the column as a second paramter if not using 'user_id'
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $fillable = [
'title',
'content'
];
// returns User that belongs to post
public function user() {
return $this->belongsTo('App\User');
}
}
<?php
use App\Post; // importing Post model
use App\User; // import User model
// Get a post that belongs to this user
Route::get('/user/{id}/post', function($id) {
return User::find($id)->post; // get post
// return User::find($id)->post->title; // get post title only
});
// Get the user that belongs to a post
Route::get('/post/{id}/user', function($id) {
return Post::find($id)->user->name; // get user's name
});