我构建了我们的会员级别,每个人都有限制可以保存到数据库的记录数。 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