I am having real problems getting Laravel's Eloquent ORM to return data for a relationship.
Schema::table('users', function($table)
{
$table->engine = 'InnoDB';
$table->create();
$table->increments('id')->unsigned();
$table->string('firstname');
$table->string('surname');
$table->string('email')->unique();
$table->string('password')->unique();
$table->string('phone')->nullable();
$table->text('about')->nullable();
$table->timestamps();
});
Schema::table('files', function($table)
{
$table->engine = 'InnoDB';
$table->create();
$table->increments('id')->unsigned();
$table->string('filename');
$table->string('title');
$table->text('description')->nullable();
$table->string('keywords')->nullable();
$table->integer('category_id')->unsigned();
$table->integer('file_type_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->timestamps();
});
<?php
class File extends Eloquent
{
public static $timestamps = true;
public function user()
{
return $this->belongs_to('User');
}
}
<?php
class User extends Eloquent
{
public static $timestamps = true;
public function files()
{
return $this->has_many('File');
}
}
// everything else in my routes.php is as it was when downloaded
Route::get('users', function()
{
echo '<pre>';
// this works
$users = User::all();
print_r($users);
// this doesn't work
print_r($users->files);
// this doesn't work
$files = User::find(1)->files;
print_r($files);
});
Unhandled Exception
Message:
Trying to get property of non-object Location:
C:\wamp\www\l3_mlib\application\routes.php on line 51 Stack Trace:
#0 C:\wamp\www\l3_mlib\laravel\laravel.php(42): Laravel\Error::native(8, 'Trying to get p...', 'C:\wamp\www\l3_...', 51) #1 C:\wamp\www\l3_mlib\application\routes.php(51): Laravel{closure}(8, 'Trying to get p...', 'C:\wamp\www\l3_...', 51, Array) #2 [internal function]: {closure}() #3 C:\wamp\www\l3_mlib\laravel\routing\route.php(163): call_user_func_array(Object(Closure), Array) #4 C:\wamp\www\l3_mlib\laravel\routing\route.php(124): Laravel\Routing\Route->response() #5 C:\wamp\www\l3_mlib\laravel\laravel.php(167): Laravel\Routing\Route->call() #6 C:\wamp\www\l3_mlib\public\index.php(34): require('C:\wamp\www\l3_...') #7 {main}
What am I doing wrong?
I had the same issue with a model called Task which is a Laravel class also.
In application/config/application.php there are some class aliases that remove the namespacing. You can comment out the File alias, then it will not clash with yours.
If you then need to use the Laravel File class at any point, you can refer to it via its namespaced name, e.g.
Laravel\\File::get('path/to/file');
Hope this helps,
Dan