Laravel 在模型中定义的视图中调用方法。不起作用
我的观点中有很多逻辑。我在我的一个模型中将其重构为方法。它们正在被识别,但实际上并不工作,因为IF不会随着数据库的改变而改变,以反映应该调用的不同方法 例如,我的代码最初是这样的,所有的逻辑都在视图中Laravel 在模型中定义的视图中调用方法。不起作用,laravel,laravel-5,eloquent,Laravel,Laravel 5,Eloquent,我的观点中有很多逻辑。我在我的一个模型中将其重构为方法。它们正在被识别,但实际上并不工作,因为IF不会随着数据库的改变而改变,以反映应该调用的不同方法 例如,我的代码最初是这样的,所有的逻辑都在视图中 @if($tenancy == null || $tenancy->accepted == 0 && $tenancy->request_sent != 1) <a href="/account/tenancy/{{$user->
@if($tenancy == null || $tenancy->accepted == 0 && $tenancy->request_sent != 1)
<a href="/account/tenancy/{{$user->id}}/create" class="btn btn-primary">Start Tenancy</a>
@endif
<!--
If the user signed in isn't the owner of this profile.
Do not show these buttons that control accept/reject/end
-->
@if(Auth::user()->id == $user->id)
<!--
If the request has been sent but hasn't been accepted.
Give the option to accept and reject.
This updates the values in DB.
-->
@if($tenancy != null && $tenancy->accepted == 0 && $tenancy->request_sent == 1)
<form method="POST" action="/account/tenancy/{{$user->id}}/accept">
{{ csrf_field() }}
<input type="submit" class="btn btn-primary" value="Accept Request">
</form>
<form method="POST" action="/account/tenancy/{{$user->id}}/reject">
{{ csrf_field() }}
<input type="submit" class="btn btn-warning" value="Reject Request">
</form>
<!--
If the request has been accepted.
Show button to end the tenancy,
and property details
-->
@elseif($tenancy != null && $tenancy->accepted == 1 && $tenancy->request_sent == 0)
<form method="POST" action="/account/tenancy/{{$user->id}}/end">
{{ csrf_field() }}
<input type="submit" class="btn btn-primary" value="End Tenancy">
</form>
<h5>Currently in Tenancy with {{$tenancy->landlord_name}}</h5>
<h5>Your property is {{$tenancy->property_address}}</h5>
@endif <!-- End of current user vs this user-->
@endif <!-- Initial If-->
这是定义方法的租赁模型
public function addTenancy()
{
return $this->accepted == 0 && $this->request_sent == 0;
}
public function hasRequestPending()
{
return $this->accepted == 0 && $this->request_sent == 1;
}
public function inTenancy()
{
return $this->accepted == 1 && $this->request_sent == 0;
}
我不明白为什么新的更新视图不应该随着数据库的变化而在IF语句中移动。有什么想法吗?我认为您不能从数据库中获取雄辩的模型,而只能从表“租约”中获取第一行。您应该这样做
$book=App\book::first()代码>但首先您必须将您的模型连接到数据库@cash非常完美,非常感谢。如果您不想将此作为正式答案,我将接受最佳答案。您可能希望同时使用租赁
和租赁
作为变量名进行更改。“真令人困惑。”罗伯特。好主意。当数据库为空时,这不会失败吗?@Robert this将返回null,因此您应该检查该变量以避免不必要的错误
public function index($id){
$user = User::where('id', $id)->first();
$users = Auth::user();
$Tenancy = new Tenancy;
$tenancy = DB::table('tenancy')->first();
return view('/pages/account/index', compact('user', 'users', 'Tenancy', 'tenancy'));
}
public function addTenancy()
{
return $this->accepted == 0 && $this->request_sent == 0;
}
public function hasRequestPending()
{
return $this->accepted == 0 && $this->request_sent == 1;
}
public function inTenancy()
{
return $this->accepted == 1 && $this->request_sent == 0;
}