0
votes

This is baffling me and cannot see anything wrong and google hasnt helped.

I have a one to many relationship in Laravel in EmailService model and EmailServiceType model.

I keep getting the below error:

"message": "Call to undefined relationship [services] on model [App\EmailServiceType].", "exception": "Illuminate\Database\Eloquent\RelationNotFoundException", "file": "/home/vagrant/Code/WebDevMarket/vendor/laravel/framework/src/Illuminate/Database/Eloquent/RelationNotFoundException.php", "line": 34, "trace": [

Below are my models and controller function:

App\EmailService.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class EmailService extends Model
{
    public function type()
    {
        return $this->belongsTo('App\EmailServiceType', 'type_id', 'id')->withTimestamps();
    }
}

App\EmailServiceType.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class EmailServiceType extends Model
{
    public const SES = 1;
    public const SENDGRID = 2;
    public const MAILGUN = 3;
    public const POSTMARK = 4;
    public const MAILJET = 5;

    /** @var array */
    protected static $types = [
        self::SES => 'SES',
        self::SENDGRID => 'Sendgrid',
        self::MAILGUN => 'Mailgun',
        self::POSTMARK => 'Postmark',
        self::MAILJET => 'Mailjet',
    ];

    /**
     * Resolve a type ID to a type name.
     */
    public static function resolve(int $typeId): ?string
    {
        return static::$types[$typeId] ?? null;
    }

    public function services()
    {
    return $this->hasMany('App\EmailService', 'type_id', 'id')->withTimestamps();
    }    
}

EmailServiceController.php function

public function GetTypes()
    {

        $Type = EmailServiceType::with('services')->get();

        return EmailServiceResource::collection($Type);
    }

Any help in advance is greatly appreciated.

2

2 Answers

0
votes

You don't need to give reference id, try this:

    public function services()
    {
      return $this->hasMany('App\EmailService');
    }     
0
votes

Turns out it was the use of withTimestamps(); that was causing the issue. This is a laravel method reserved for pivot tables only.

Sorted thanks to isamaile at laracasts.