Dalma
6 months ago

Weird namespacing issue?

Posted 6 months ago by Dalma

I have a model named Schedule that has an unexpected namespacing issue, it behaves differently than my other models. Laravel 5.7

I will contrast two models

Schedule (not working as expected - this is also my first polymorphic model)

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Spatie\Activitylog\Traits\LogsActivity;


class Schedule extends Model
{
    use LogsActivity;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'schedules';

    /**
    * The database primary key value.
    *
    * @var string
    */
    protected $primaryKey = 'id';

    /**
     * Attributes that should be mass-assignable.
     *
     * @var array
     */
    protected $fillable = ['start_dt', 'end_dt', 'note', 'schedulable_id', 'schedulable_type'];

    public function schedulable()
    {
        return $this->morphTo();
    }
}

Task model that works as expected

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Spatie\Activitylog\Traits\LogsActivity;
use App\Events\TaskUpdated;


class Task extends Model
{
    use LogsActivity;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'tasks';

    /**
    * The database primary key value.
    *
    * @var string
    */
    protected $primaryKey = 'id';

    /**
     * Attributes that should be mass-assignable.
     *
     * @var array
     */
    protected $fillable = ['phase_id', 'name', 'start_date', 'end_date', 'required', 'stage_id', 'tech_id', 'notes', 'technotes', 'status_id', 'dependant_upon', 'weight'];

    protected static $logFillable = true;

    public function phase()
    {
        return $this->belongsTo('App\Phase');
    }
    public function stage()
    {
        return $this->belongsTo('App\Stage');
    }
    public function tech()
    {
        return $this->belongsTo('App\User');
    }
    public function status()
    {
        return $this->belongsTo('App\Status');
    }
    public function user()
    {
        return $this->belongsTo('App\User');
    }

    public function schedules()
    {
        return $this->morphMany('App\Schedule','schedulable');
    }

    protected $dispatchesEvents = [
      'updated' =>   TaskUpdated::class,
    ];
}

from the following tinker commands

Task::first()

This returns the first model as expected

Schedule::first()

This fails with the message PHP Fatal error: Class 'Schedule' not found

App\Schedule::first()

This works

Both of the models are in the normal laravel file structure in the app directory.

Is Schedule perhaps a reserved word or have I overlooked the obvious?

Please sign in or create an account to participate in this conversation.