laravel Model hasOne code example
Example 1: laravel hasOne
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function phone()
{
return $this->hasOne('App\Phone');
}
}
Example 2: laravel detach
$user->roles()->detach($roleId);
$user->roles()->detach();
Example 3: laravel belongs to
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Phone extends Model
{
public function user()
{
return $this->belongsTo('App\Models\User');
}
}
Example 4: laravel has many
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function comments()
{
return $this->hasMany('App\Models\Comment');
}
}