From 57495d36d816c8a46d1ff3ee0ffcc242260185fc Mon Sep 17 00:00:00 2001 From: hackerESQ Date: Fri, 25 Oct 2024 22:06:46 -0500 Subject: [PATCH] fix:optimize portfolio_users query --- app/Models/Portfolio.php | 7 ++++++- resources/views/portfolio/show.blade.php | 6 +++++- tests/PortfolioPolicyTest.php | 9 +++++---- 3 files changed, 16 insertions(+), 6 deletions(-) diff --git a/app/Models/Portfolio.php b/app/Models/Portfolio.php index dec7543..e91d273 100644 --- a/app/Models/Portfolio.php +++ b/app/Models/Portfolio.php @@ -107,7 +107,12 @@ class Portfolio extends Model public function getOwnerAttribute() { - return $this->users()->firstWhere('owner', 1); + if (!$this->relationLoaded('user')) { + + $this->load('users'); + } + + return $this->users->where('pivot.owner', true)->first(); } public static function ensurePortfolioHasOwner(self $portfolio) diff --git a/resources/views/portfolio/show.blade.php b/resources/views/portfolio/show.blade.php index eeb9274..b2979c9 100644 --- a/resources/views/portfolio/show.blade.php +++ b/resources/views/portfolio/show.blade.php @@ -25,7 +25,11 @@ @if($portfolio->wishlist) - + + @endif + + @if(auth()->user()->id !== $portfolio->owner_id) + @endif @can('fullAccess', $portfolio) diff --git a/tests/PortfolioPolicyTest.php b/tests/PortfolioPolicyTest.php index 670354f..4b040e5 100644 --- a/tests/PortfolioPolicyTest.php +++ b/tests/PortfolioPolicyTest.php @@ -14,6 +14,7 @@ class PortfolioPolicyTest extends TestCase use RefreshDatabase; protected $policy; + protected $owner; protected $user; protected $portfolio; @@ -23,12 +24,12 @@ class PortfolioPolicyTest extends TestCase $this->policy = new PortfolioPolicy(); - $this->user = User::factory()->create(); - - Auth::login($this->user); + $this->owner = User::factory()->create(); + Auth::login($this->owner); $this->portfolio = Portfolio::factory()->create(); // Attach the users to the portfolio + $this->user = User::factory()->create(); $this->portfolio->users()->syncWithoutDetaching([ $this->user->id => [ 'full_access' => false, @@ -37,7 +38,7 @@ class PortfolioPolicyTest extends TestCase ]); } - public function test_stranger_access_viaweb() + public function test_stranger_access_via_web() { $user = User::factory()->create();