我構建了我們的會員級別,每個人都有限制可以保存到數據庫的記錄數。 laracasts上的某人表示我想檢查observer中的會員級別限制,如果達到限制,則將其重定向到上一頁並顯示錯誤。如果達到數據庫記錄限制返回到上一頁的消息
這似乎是工作,除了它重定向的限制已達到並創建記錄的消息。理想情況下,如果達到限制,則不應創建記錄。我不知道我在做什麼錯,我也試圖return false;
而不是return back();
,但那也沒用。
(通過,如果有一個更簡單的方法來做到這一點的方式,我所有的耳朵)
這裏是我的觀察:
<?php
namespace App\Observers;
use App\Company;
use Auth;
use Session;
class SubscriptionLimits {
public function __construct(){
$this->company = Auth::user()->company_id;
}
public function creating()
{
try {
$company = Company::find($this->company);
$clients = \App\Client::where(['company_id' => $this->company])->count();
$contacts = \App\Contact::where(['company_id' => $this->company])->count();
$leads = \App\Lead::where(['company_id' => $this->company])->count();
$opportunities = \App\Opportunity::where(['company_id' => $this->company])->count();
$invoices = \App\Invoice::where(['company_id' => $this->company])->count();
$estimates = \App\Estimate::where(['company_id' => $this->company])->count();
$proposals = \App\Proposal::where(['company_id' => $this->company])->count();
$projects = \App\Project::where(['company_id' => $this->company])->count();
$tasks = \App\Task::where(['company_id' => $this->company])->count();
$boards = \App\Board::where(['company_id' => $this->company])->count();
$bulletins = \App\Bulletin::where(['company_id' => $this->company])->count();
$cards = \App\Card::where(['company_id' => $this->company])->count();
$lineitems = \App\LineItem::where(['company_id' => $this->company])->count();
$notes = \App\Note::where(['company_id' => $this->company])->count();
$timer = \App\Timer::where(['company_id' => $this->company])->count();
$templates = \App\Template::where(['company_id' => $this->company])->count();
$userExtra = \App\UserExtra::where(['company_id' => $this->company])->count();
$count = $clients + $contacts + $leads + $opportunities + $invoices + $estimates + $proposals + $projects + $tasks + $boards + $bulletins + $cards + $lineitems + $notes + $timer + $templates + $userExtra;
if($count >= 5 && !$company->subscriptions){ //Free tier throw error because limit is reached
//return false; //Works but throws error
Session::flash('error', 'You have reached your record limit, please <a href="/order">upgrade now</a> to continue');
return back();
}
if($company->subscribed('middle_tier_monthly_per_user') || $company->subscribed('middle_tier_annual_per_user')){
if($count > 10){ //If middle tier and limit is reached
//return false; //Works but throws error
Session::flash('error', 'You have reached your record limit, please <a href="/order">upgrade now</a> to continue');
return back();
}
}
} catch (Exception $e) {
Session::flash('error', 'You have reached your record limit, please <a href="/order">upgrade now</a> to continue');
return back();
}
}
}
更新問題 Here is a video,這不應該讓我創建一個記錄,而應該返回達到的限制消息並提示我升級。
首先,當你捕捉異常的消息應該是不同的。如果您聲稱錯誤是達到了限制,但實際上還有其他內容(例如數據庫處於脫機狀態),那麼每個人都會誤導他人。 (另外,'use Exception') – apokryfos