我通过控制器方法将$notifications
发送到主视图,并在网站标题上显示通知。
“个人资料”视图扩展了主视图,我还想在个人资料视图上显示通知。
但是当我请求个人资料视图时,它会生成一个错误,未定义变量$ notifications。
我认为一种解决方案是从控制器方法返回配置文件视图时发送$notifications
,但是在网站上,我想在其中显示通知选项卡的视图很多,这是我所认为的正确方法
我通过以下方式返回了主视图
return view('home')->with(['unseen_notification_counter'=>$unseen_notification_counter,'notifications'=>$notifications]);
这是标题部分主视图中的代码
<ul class="dropdown-menu" id="notificationlist">
@foreach($notifications as $notification)
<li>
<a href="{{route('user.profile',$notification->id)}}" class="dropdown-item">
<img src="http://localhost/webproject/public/user_images/{{$notification->image}}" class="img-thumbnil" width="20px" height="20px">
<strong>{{$notification->username}}</strong>
<span style="white-space: initial;">sent you a friend request.</span>
</a>
</li>
@endforeach
</ul>
答案 0 :(得分:3)
如果要将相同的数据传递到应用程序中的多个视图,则可以使用View Composers
例如在AppServiceProvider的Get-ADUser -SearchBase "DC=corp,DC=companyx,DC=com" -Filter * -Properties ProxyAddresses,sn,givenname,displayname,mail |
Where-object {($_.ProxyAddresses -cmatch "SMTP:") -and ($_.ProxyAddresses -match "$($_.givenname).$($_.sn)*")}
方法中,您将看到类似
boot()
然后,您只需将不同的刀片文件名(就像使用路由一样)添加到阵列中即可。
或者,您可以share包含所有视图的通知:
public function boot()
{
view()->composer(['home', 'profile'], function ($view) {
$notifications = \App\Notification::all(); //Change this to the code you would use to get the notifications
$view->with('notifications', $notifications);
});
}
答案 1 :(得分:1)
创建一个BaseController
,然后从那里共享数据:
<?php
namespace App\Http\Controllers;
use View;
//You can create a BaseController:
class BaseController extends Controller {
public $dataVariable = "some data";
public function __construct() {
$anotherVariable = "more data";
$notifications = Notification::where('is_seen',0)->get(); // assuming this gets unseen notifications
$unseen_notification_counter = count($notifications);
View::share ( 'notifications', $notifications );
View::share ( 'unseen_notification_counter', $unseen_notification_counter );
View::share ( 'data_variable', $this->dataVariable );
View::share ( 'another_variable', $this->anotherVariable );
}
}
所有扩展BaseController
的控制器将有权访问数据。做这样的事情:
class DashboardController extends BaseController {
public function Index(){
return view('index'); // all the shared data is available in the view ($notifications and $unseen_notification_counter)
}
}
希望它能起作用。