【发布时间】:2021-08-22 18:56:57
【问题描述】:
我在 Laravel 7 中有一个项目,该项目在用户表中有一个名为 organ_id 的列,它为不同的用户(1,2,...)提供不同的数字
现在我想在我的控制器内部使用organ_id,如下,通过使用if,根据器官编号给每个用户不同的信息。
ProductsController.php
namespace App\Http\Controllers;
use App\User;
use DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
if (Auth::check())
{
$organ_id = Auth::user()->getId();
}
class ProductsController extends Controller
{
public function test(Request $request) {
if ($organ_id == 1) {
function orders(Request $request) {
$data = DB::table('products_1')
->orderBy('id', 'asc')
->paginate(14);
return view('products', compact('data'));
}
function posts(Request $request) {
$data = DB::table('posts')
->orderBy('id', 'asc')
->paginate(25);
return view('posts', compact('data'));
}
/*
other functions
.
.
.
*/
}
if ($organ_id == 2) {
function orders(Request $request) {
$data = DB::table('products_2')
->orderBy('id', 'asc')
->paginate(14);
return view('products', compact('data'));
}
function posts(Request $request) {
$data = DB::table('posts')
->orderBy('writer_id', 'asc')
->paginate(10);
return view('posts', compact('data'));
}
/*
other functions
.
.
.
*/
}
}
}
User.php
public function getId()
{
return $this->organ_id;
}
由于不能在控制器中使用if,所以我写了public function test()并将if放在这个函数中。
很遗憾,在这种情况下,浏览器找不到下单功能。
【问题讨论】:
-
天哪,我真的很抱歉对你这么苛刻,但是你的代码太可怕了,我从来没有像你那样在
method中看到function,那是绝对的NO-NO。那个代码真的很糟糕。你不要在class之外写任何东西(除了namespace和use),那个if是不正确的,应该在方法test里面。还有那些functions,你想用posts、organs等做什么?您不创建function并返回函数...解释 100% 您想要实现的目标。用那个代码。另外,请阅读文档,因为不推荐这样做