我有几个查询,我想将它用于同一个控制器中的几个方法。例如下面的代码:
$lastlogin = User::select('lastlogin')->where('id',Auth::user()->id)->get()->pluck('lastlogin');
$bio = User::where('id',Auth::user()->id)->value('bio');
$photo = User::where('id',Auth::user()->id)->value('photo');
$notifications = Notification::where('created_at','>',$lastlogin)->get();
$status = User::where('id',Auth::user()->id)->value('search_status');
我需要在UserController中的4个方法中调用上面的查询。
我想做类似的事情:
public function john_doe()
{
$lastlogin = User::select('lastlogin')->where('id',Auth::user()->id)->get()->pluck('lastlogin');
$bio = User::where('id',Auth::user()->id)->value('bio');
$photo = User::where('id',Auth::user()->id)->value('photo');
$notifications = Notification::where('created_at','>',$lastlogin)->get();
$status = User::where('id',Auth::user()->id)->value('search_status');
}
然后
UserController
public abc (){john_doe();}
public def (){john_doe();}
public ghi (){john_doe();}
public jkl (){john_doe();}
但是我收到了一个错误。我如何做到这一点,当我在一个地方更改代码时,它反映在哪里?
public function notify()
{
$bio = User::where('id',Auth::user()->id)->value('bio');
$photo = User::where('id',Auth::user()->id)->value('photo');
$friends = Friend::where('user_id',Auth::user()->id)->where('reqs_status',2)->get();
$notifications = Notification::where('created_at','>',Auth::user()->lastlogin)->get();
$status = User::where('id',Auth::user()->id)->value('search_status');
}
public function index()
{
$this->notify();
return view('/users/index',compact('send_requests','accept_rejects','sent_requests','users','bio','photo','friends','status','seeks','filters','notifications'));
}
答案 0 :(得分:1)
您的UserController
看起来像这样
class UserController extends BaseController {
public function notify()
{
$array['bio'] = User::where('id',Auth::user()->id)->value('bio');
$array['photo'] = User::where('id',Auth::user()->id)->value('photo');
$array['friends'] = Friend::where('user_id',Auth::user()->id)->where('reqs_status',2)->get();
$array['notifications'] = Notification::where('created_at','>',Auth::user()->lastlogin)->get();
$array['status'] = User::where('id',Auth::user()->id)->value('search_status');
return $array;
}
public function index()
{
return view('/users/index', $this->notify());
}
}
答案 1 :(得分:1)
这是一个写得不好的代码。除了登录用户模型的通知外,您将获得所有内容。
public function fetchData()
{
$user = auth()->user();
$notifications = Notification::where('created_at', '>' , $user->lastlogin)->get();
$data = [
'lastlogin' => $user->lastlogin,
'bio' => $user->bio,
'photo' => $user->photo,
'search_status' => $user->search_status,
'notifications' => $notifications,
];
return (Object)$data;
}
public function test()
{
$data = $this->fetchData();
// $data->lastlogin;
// $data->bio;
// $data->photo;
// $data->search_status;
// $data->notifications;
}