Laravel Snippets (v.1.13.0): Problems with relationships (One-To-Many, …)

  laravel, relationship, visual-studio-code

Introduction
I’m using this Add-on for Visual Studio Code.
When creating relations with it. My views seem not working. I get an error in the browser (see below).

Laravel Snippets ID: onecentlin.laravel5-snippets Beschreibung:
Laravel snippets for Visual Studio Code (Support Laravel 5 and above)
Version: 1.13.0 Herausgeber: Winnie Lin Link zum Visual Studio
Marketplace: https://marketplace.visualstudio.com/items?itemName=onecentlin.laravel5-snippets

My Model

<?php

namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;

class Person extends Model
{
    use HasFactory;
    protected $fillable = [];

    /**
     * Get the phone associated with the Person
     *
     * @return IlluminateDatabaseEloquentRelationsHasOne
     */
    public function phone(): HasOne
    {
        return $this->hasOne(Phone::class);
    }
}

Error shown by the browser, when calling the view

TypeError Return value of AppModelsPerson::phone() must be an instance of
AppModelsHasOne, instance of
IlluminateDatabaseEloquentRelationsHasOne returned (View:
C:UsersMusaSaglamcomponenttestresourcesviewstestindex.blade.php)

My view

<x-layout>

    <main class="main" id="top">
      <div class="container" data-layout="container">
        <script>
          var isFluid = JSON.parse(localStorage.getItem('isFluid'));
          if (isFluid) {
            var container = document.querySelector('[data-layout]');
            container.classList.remove('container');
            container.classList.add('container-fluid');
          }
        </script>
  
        <x-nav.admin-nav/>
        <div class="content">
            <x-nav.admin-nav-top/>

            <h1>People</h1>
            @foreach ($people as $person)
                <h2>{{ $person->id }}</h2>
                <h2>{{ $person->phone->number }}</h2>
            @endforeach


        </div>
      </div>
    </main>
  </x-layout>

But if I remove : HasOne after public function phone() in my model. Everything works fine.

Two questions

  • Why does the Snippet adds : HasOne. What is the benefit of this?
  • Does not make it easier for users like me using the snippet without : HasOne?
    I’m a beginner and I could not understand why the tutorials did not work.

Source: Laravel

Leave a Reply