Skip to content

Instantly share code, notes, and snippets.

@Naoray
Created January 11, 2018 09:19
Show Gist options
  • Save Naoray/7a36b8c082063aeb152a47d42c95a02c to your computer and use it in GitHub Desktop.
Save Naoray/7a36b8c082063aeb152a47d42c95a02c to your computer and use it in GitHub Desktop.
Accessor can't be accessed through HasMany Relationship
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
public function getFooAttribute()
{
return 'Bar';
}
public function users()
{
return $this->hasMany(User::class);
}
}
<?php
namespace App\Http\Controllers;
class TestController extends Controller
{
public function index()
{
App\Project::first()->foo; // prints 'Bar'
App\User::first()->bar; // prints 'Foo'
App\Project::first()->users->first()->bar; // prints 'null'
App\User::first()->project->foo; // prints 'null'
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function getBarAttribute()
{
return 'Foo';
}
public function project()
{
return $this->belongsTo(Project::class);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment