# Relationships sử dụng hasOne, belongsTo (ok)

## Ví dụ 1:

app\User.php

```
public function address() {
    return $this->hasOne(Address::class);
}
```

routes\web.php

```
Route::get('/user', function(){
  $users = \App\User::all();
   return view('users.index',compact('users'));
});
```

resources\views\users\index.blade.php

```
@extends('layouts.app')
@section('content')
<div class="row justify-content-center">
	<div class="col-md-8">
		<div class="card">
			@foreach ($users as $user)
				<h2>{{$user->name}}</h2>
				<p>{{$user->address->country}}</p>
			@endforeach
		</div>
	</div>
</div>
@endsection
```

app\Address.php

```
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Address extends Model
{
    protected $fillable = [
        'user_id', 'country'
    ];
}
```

database\migrations\2014\_10\_12\_000000\_create\_users\_table.php

```
public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });
}
```

database\migrations\2020\_08\_06\_083302\_create\_addresses\_table.php

```
public function up()
{
    Schema::create('addresses', function (Blueprint $table) {
        $table->id();
        $table->bigInteger('user_id');
        $table->string("country");
        $table->timestamps();
    });
}
```

Kết quả:

![](https://1957079826-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MCBeDUD-PK_RF-YgJRe%2F-ME2-o5eRWKLT6C0jn4M%2F-ME2CnNprIBBog9qkImP%2FScreenshot_6.png?alt=media\&token=ae8b1e35-4d7c-40c1-b238-d20a1ef1efc5)

## Ví dụ 2:

C:\xampp\htdocs\hanam.com\app\Http\Controllers\HomeController.php

```
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller {
  /**
   * Create a new controller instance.
   *
   * @return void
   */
  public function __construct() {
    $this->middleware('auth');
  }
  /**
   * Show the application dashboard.
   *
   * @return \Illuminate\Contracts\Support\Renderable
   */
  public function index() {
    return view('home');
  }
}
```

C:\xampp\htdocs\hanam.com\app\Address.php

```
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Address extends Model {
  protected $fillable = [
    'user_id', 'country',
  ];
}
```

C:\xampp\htdocs\hanam.com\app\User.php

```
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
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',
  ];
  /**
   * The attributes that should be cast to native types.
   *
   * @var array
   */
  protected $casts = [
    'email_verified_at' => 'datetime',
  ];
  public function address() {
    return $this->hasOne(Address::class);
  }
}
```

C:\xampp\htdocs\abc\index.blade.php

```
@extends('layouts.app');
@section('content')
<div class="row justify-content-center">
	<div class="col-md-8">
		<div class="card">
			@foreach ($users as $user)
				<h2>{{$user->name}}</h2>
				<p>{{$user->address->country}}</p>
			@endforeach
		</div>
	</div>
</div>
@endsection
```

C:\xampp\htdocs\hanam.com\routes\web.php

```
<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
  return view('welcome');
});
Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');
// Route::get('/user', function(){
//   factory(\App\User::class,5)->create();
// });
Route::get('/user', function(){
 $users = \App\User::all();
 return view('users.index',compact('users'));
});

```

![](https://1957079826-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MCBeDUD-PK_RF-YgJRe%2F-ME2rxjA-pf8Wf3e2wSW%2F-ME2suN_ejvkPyBtkyPU%2FScreenshot_1.png?alt=media\&token=f431f11a-941e-4604-a472-e73c4db511ab)

## Ví dụ 3: sử dụng belongsTo

C:\xampp\htdocs\hanam.com\app\Address.php

```
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Address extends Model {
  protected $fillable = [
    'user_id', 'country',
  ];
  public function user() {
  	return $this->belongsTo(User::class);
  }
}
```

C:\xampp\htdocs\hanam.com\resources\views\users\index.blade.php

```
@extends('layouts.app')
@section('content')
<div class="row justify-content-center">
	<div class="col-md-8">
		<div class="card">
			{{-- @foreach ($users as $user)
				<h2>{{$user->name}}</h2>
				<p>{{$user->address->country}}</p>
			@endforeach --}}
			@foreach ($addresses as $address)
				<h2>{{$address->country}}</h2>
				<p>{{$address->user->name}}</p>
			@endforeach
		</div>
	</div>
</div>
@endsection
```

C:\xampp\htdocs\hanam.com\app\User.php

```
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
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',
  ];
  /**
   * The attributes that should be cast to native types.
   *
   * @var array
   */
  protected $casts = [
    'email_verified_at' => 'datetime',
  ];
  public function address() {
    return $this->hasOne(Address::class);
  }
}
```

C:\xampp\htdocs\hanam.com\routes\web.php

```
<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
 */

Route::get('/', function () {
  return view('welcome');
});
Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');
// Route::get('/user', function(){
//   factory(\App\User::class,5)->create();
// });
Route::get('/user', function () {
	// $user  = factory(\App\User::class)->create();
	// \App\Address::create([
	// 	"user_id" => $user->id,
	// 	"country" => "Ha Nam 10"
	// ]);
	// $user->address()->create([
	// 	"country" => "Ha Nam 9"
	// ]);
  // $users = \App\User::all();
  $addresses = \App\Address::all();
  return view('users.index', compact('addresses'));
});

```

![](https://1957079826-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MCBeDUD-PK_RF-YgJRe%2F-ME3B-yF_nHSIVgB2XQJ%2F-ME3B5F7Us_wPdBeKarP%2FScreenshot_3.png?alt=media\&token=e14e40f2-6bac-4863-afd9-efbbe2320608)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://learnphp.gitbook.io/learnphp/learn-lavarel/relationships-su-dung-hasone-ok.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
