Created
January 11, 2018 09:19
-
-
Save Naoray/7a36b8c082063aeb152a47d42c95a02c to your computer and use it in GitHub Desktop.
Accessor can't be accessed through HasMany Relationship
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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' | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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