如何将公共函数header的$id传递至index2的whereNotIn中
解决方案:在
index2()中获取header()里的$id变量 假设这两个公共方法属于同一个类(比如Laravel控制器),这里有几种实用的实现方式,你可以根据实际场景选择:
1. 将$id作为类属性共享
这是同类方法间共享变量最常用的方式,把$id存储在类的成员属性中,两个方法都能直接访问:
class YourController extends Controller { // 定义类属性,可根据访问需求设为private/public private $sharedId; public function header() { // 这里是你生成或获取$id的逻辑 $this->sharedId = 123; // 你的其他header方法逻辑,比如返回视图、处理响应等 return view('header'); } public function index2() { // 注意:如果是同请求内调用,要先确保header()已执行,否则$this->sharedId会为null $this->header(); // 直接使用类属性中的id进行查询 $records = YourModel::whereNotIn('column_name', [$this->sharedId])->get(); // 你的其他index2业务逻辑 return view('index2', compact('records')); } }
注意:如果header()和index2()处理的是两个独立HTTP请求(比如用户先访问header路由,再访问index2路由),这种方式会失效——因为每次请求都会生成新的控制器实例,类属性会被重置,此时可参考下面的Session方案。
2. 让header()返回$id,在index2()中接收
如果header()的返回值可以调整,直接让它返回$id(或包含$id的数组),再在index2()中调用并接收:
public function header() { $id = 123; // 获取或生成id的逻辑 // 如果原本header()需要返回视图,可改成返回包含id和视图的数组 return [ 'id' => $id, 'view' => view('header') ]; } public function index2() { // 调用header()拿到返回的id $headerData = $this->header(); $targetId = $headerData['id']; // 使用id执行查询 $records = YourModel::whereNotIn('column_name', [$targetId])->get(); // 若需要用到header的视图内容,可通过$headerData['view']调用 return view('index2', compact('records')); }
3. 跨请求共享:用Session存储$id
如果header()和index2()属于不同的HTTP请求,必须用持久化存储传递$id,Session是最便捷的选择:
public function header() { $id = 123; // 获取或生成id的逻辑 // 将id存入session session(['target_id' => $id]); return view('header'); } public function index2() { // 从session取出id,记得判断是否存在避免报错 $targetId = session('target_id'); if (!$targetId) { // 处理id不存在的情况,比如跳转回header页面或提示错误 return redirect()->route('header')->with('error', '请先访问header页面'); } $records = YourModel::whereNotIn('column_name', [$targetId])->get(); return view('index2', compact('records')); }
4. 直接重新获取$id(如果来源公共)
如果header()里的$id来自请求参数、数据库或其他公共来源,完全可以在index2()中直接重新获取,避免方法间的耦合:
public function header() { // 从请求参数获取id $id = request()->input('user_id'); // 其他header逻辑 } public function index2() { // 直接从请求重新获取id,无需依赖header() $id = request()->input('user_id'); $records = YourModel::whereNotIn('column_name', [$id])->get(); // 其他index2逻辑 }
内容的提问来源于stack exchange,提问作者Valter Sousa Cardoso
相关产品推荐
相关产品推荐

