# Relationships

> In addition to the variety of fields we've already discussed, Laravel Rest Api has full support for all of Laravel's relationships. After adding relationships to your REST resources, you'll be able to directly access them from the requested resource, eliminating the need for multiple API calls.

Be aware that all relations must be declared in the resource even though they'll be linked to Laravel relationships. You can't link models without using a resource. This allows Laravel Rest Api to take full advantage of Rest Resources to make your requests powerful and secure.

Your relationships should all be declared in the "relations" method of your resource:

```php
class ModelResource extends Resource
{
    public function relations(RestRequest $request)
    {
        return [
            HasOne::make('hasOneRelation', HasOneResource::class),
            BelongsTo::make('belongsToRelation', BelongsToResource::class),
            HasMany::make('hasManyRelation', HasManyResource::class),
            BelongsToMany::make('belongsToManyRelation', BelongsToManyResource::class)
                ->withPivotFields(['created_at']),
        ];
    }
}
```

The first argument of the relation is the name of the relationship in your model, the second one is the linked resource(s).

## Has One

The `HasOne` relation corresponds to a `hasOne` Eloquent relationship. For example, let's assume a User model hasOne Address model. We may add the relationship to our User Rest resource like so:

```php
use Lomkit\Rest\Relations\HasOne;

HasOne::make('address', AddressResource::class),
```

### Has One Of Many

The `HasOneOfMany` relation corresponds to a `hasOne ofMany` Eloquent relationship. For example, let's assume a Restaurant model hasOneOfMany Order model. We may add the relationship to our Restaurant Rest resource like so:

```php
use Lomkit\Rest\Relations\HasOneOfMany;

HasOneOfMany::make('order', OrderResource::class),
```

## Has Many

The `HasMany` relation corresponds to a `hasMany` Eloquent relationship. For example, let's assume a User model hasMany Post models. We may add the relationship to our User Rest resource like so:

```php
use Lomkit\Rest\Relations\HasMany;

HasMany::make('posts', PostResource::class),
```

## Has One Through

The `HasOneThrough` relation corresponds to a `hasOneThrough` Eloquent relationship. For example, let's assume a User model hasOne car through a Company model. We may add the relationship to our User Rest resource like so:

```php
use Lomkit\Rest\Relations\HasOneThrough;

HasOneThrough::make('car', CarResource::class),
```

<warning>

You can't mutate models using "HasOneThrough" relationships, please use a double "HasOne" relationship if you want to mutate the distant entry

</warning>

## Has Many Through

The `HasManyThrough` relation corresponds to a `hasManyThrough` Eloquent relationship. For example, let's assume a User model hasMany stars through a Company model. We may add the relationship to our User Rest resource like so:

```php
use Lomkit\Rest\Relations\HasManyThrough;

HasManyThrough::make('star', StarResource::class),
```

<warning>

You can't mutate models using "HasManyThrough" relationships, please use a "HasOne" relationship followed by a "HasMany" relationship if you want to mutate the distant entry

</warning>

## Belongs To

The `BelongsTo` relation corresponds to a `belongsTo` Eloquent relationship. For example, let's assume a User model belongsTo a Company model. We may add the relationship to our User Rest resource like so:

```php
use Lomkit\Rest\Relations\BelongsTo;

BelongsTo::make('company', CompanyResource::class),
```

## Belongs To Many

The `BelongsToMany` relation corresponds to a `belongsToMany` Eloquent relationship. For example, let's assume a User model belongsToMany Role models. We may add the relationship to our User Rest resource like so:

```php
use Lomkit\Rest\Relations\BelongsToMany;

BelongsToMany::make('roles', RoleResource::class),
```

### Pivot fields

If you want to specify pivot fields, you can achieve this by using:

```php
use Lomkit\Rest\Relations\BelongsToMany;

BelongsToMany::make('roles', RoleResource::class)->withPivotFields(['created_at']),
```

<warning>

Don't forget to specify those pivot fields on your model relationship.

<collapsible name="relations">

```php
public function roles() {
    return $this->belongsToMany(Role::class)
        ->withPivot('created_at', 'updated_at');
}
```

</collapsible>
</warning>

## MorphOne

The `MorphOne` relation corresponds to a `morphOne` Eloquent relationship. For example, let's assume a User model MorphOne Address model. We may add the relationship to our User Rest resource like so:

```php
use Lomkit\Rest\Relations\MorphOne;

MorphOne::make('address', AddressResource::class),
```

### Morph One Of Many

The `MorphOneOfMany` relation corresponds to a `morphOneOfMany` Eloquent relationship. For example, let's assume a User model MorphOneOfMany color models. We may add the relationship to our User Rest resource like so:

```php
use Lomkit\Rest\Relations\MorphOneOfMany;

MorphOneOfMany::make('color', ColorResource::class),
```

## Morph Many

The `MorphMany` relation corresponds to a `morphMany` Eloquent relationship. For example, let's assume a User model MorphMany Color models. We may add the relationship to our User Rest resource like so:

```php
use Lomkit\Rest\Relations\MorphMany;

MorphMany::make('colors', ColorResource::class),
```

## Morph To

The `MorphTo` relation corresponds to a `morphTo` Eloquent relationship. For example, let's assume a Comment model MorphTo a Post or an Video model. We may add the relationship to our Comment Rest resource like so:

```php
use Lomkit\Rest\Relations\MorphTo;

MorphTo::make('commentable', PostResource::class),
```

<warning>

You must specify multiple relations for each morph to resource possible. Please consider declaring multiple relations in your model.

<collapsible name="relations">

```php
// You can't declare this relation in Laravel Rest Api
public function commentable(): MorphTo
{
    return $this->morphTo();
}

public function post(): MorphTo
{
    return $this->morphTo('post', 'commentable_type', 'commentable_id')->whereHas('comment', function (Builder $query) {
        $query->where('commentable_type', Post::class);
    });
}

public function video(): MorphTo
{
    return $this->morphTo('video', 'commentable_type', 'commentable_id')->whereHas('comment', function (Builder $query) {
        $query->where('commentable_type', Video::class);
    });
}
```

</collapsible>
</warning>

## Morph To Many

The `MorphToMany` relation corresponds to a `morphToMany` Eloquent relationship. For example, let's assume a Post model MorphToMany Tag models. We may add the relationship to our Post Rest resource like so:

```php
use Lomkit\Rest\Relations\MorphToMany;

MorphToMany::make('taggable', TagResource::class),
```

### Defining the inverse of the relationship

As Laravel allows, you can use the "morphedByMany" relationship to define the inverse.

The `morphedByMany` relation allows to define on the `TagResource` the relation to the `PostResource` as follows:

```php
use Lomkit\Rest\Relations\MorphedByMany;

MorphedByMany::make('taggable', PostResource::class),
```

### Pivot fields

If you want to specify pivot fields, you can achieve this by using:

```php
use Lomkit\Rest\Relations\MorphToMany;
use Lomkit\Rest\Relations\MorphedByMany;

MorphToMany::make('taggable', TagResource::class)->withPivotFields(['created_at']),
MorphedByMany::make('taggable', PostResource::class)->withPivotFields(['created_at']),
```

<warning>

Don't forget to specify those pivot fields on your model relationship.

<collapsible name="relations">

```php
$this->morphToMany(Tag::class, 'taggable')->withPivot('created_at', 'updated_at');
$this->morphedByMany(Post::class, 'taggable')->withPivot('created_at', 'updated_at');
```

</collapsible>
</warning>

## Constrained Relations

In some cases you might want to constrain the relation on mutation, Laravel Rest Api offers you constraints such has `requiredOnCreation`, `prohibitedOnCreation`, `requiredOnUpdate` and `prohibitedOnUpdate`

You can apply a constraint on a relation by using:

```php
use Lomkit\Rest\Relations;

BelongsTo::make('company', CompanyResource::class)
    ->requiredOnCreation(),
```

You can also specify a closure to condition this:

```php
use Lomkit\Rest\Relations;

BelongsTo::make('company', CompanyResource::class)
    ->requiredOnCreation(function(\Lomkit\Rest\Http\Requests\RestRequest $request) {
        return true;
    }),
```
