Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel class not found with one-to-many

I'm trying to return an object Contract and all of it's related Project. I can return all of the Contracts but when I try to get the contract's Project, I get a "Class 'EstimateProject' not found" error. I've run composer dump-autoload to reload the class mappings, but I still get the error. Any ideas? Here's my class setup:

EDIT: Just wanted to add that LaravelBook\Ardent\Ardent\ is an extension of Laravel's Model.php. It adds validation to model on the Save function. I've made Ardent extend another plugin I've added that is a MongoDB version of the Eloquent ORM.

EstimateContract.php

<?php namespace Test\Tools;

  use LaravelBook\Ardent\Ardent;

  class EstimateContract extends Ardent {

     // This sets the value on the Mongodb plugin's '$collection'
     protected $collection = 'Contracts';

     public function projects()
     {
        return $this->hasMany('EstimateProject', 'contractId');
     }
  }

EstimateProject.php

<?php namespace Test\Tools;

  use LaravelBook\Ardent\Ardent;

  class EstimateProject extends Ardent {

   // This sets the value on the Mongodb plugin's '$collection'
   protected $collection = 'Projects';

   public function contract()
   {
      return $this->belongsTo('EstimateContract', 'contractId');
   }
}

EstimateContractController.php

<?php

  use  \Test\Tools\EstimateContract;

  class EstimateContractsController extends \BaseController {

/**
 * Display a listing of the resource.
 *
 * @return Response
 */
    public function index()
    {
        $contracts = EstimateContract::all();

        echo $contracts;

        foreach($contracts as $contract)
        {
            if($contract->projects)
            {
                echo $contract->projects;
            }
        }
     }
}
like image 713
Thelonias Avatar asked Aug 06 '13 15:08

Thelonias


2 Answers

In order for this to work, I needed to fully qualify the EstimateProject string in my EstimateContract model.

The solution was to change it from:

return $this->hasMany('EstimateProject', 'contractId'); 

to

return $this->hasMany('\Test\Tools\EstimateProject', 'contractId');
like image 83
Thelonias Avatar answered Nov 09 '22 12:11

Thelonias


You have to use the fully qualified name, but I got the same error when I used forward slashes instead of back slashes:

//Correct
return $this->hasMany('Fully\Qualified\ClassName');
//Incorrect
return $this->hasMany('Fully/Qualified/ClassName');
like image 2
ajon Avatar answered Nov 09 '22 10:11

ajon