我在Laravel 7中有一个项目,在用户表中有一个名为organ_id
的列,该列对不同的用户(1,2,…)有不同的数字。现在我想在我的控制器中使用organ_id
,如下所示,通过使用if
,根据器官编号给每个用户提供不同的信息。
ProductsController.php
namespace AppHttpControllers;
use AppUser;
use DB;
use IlluminateHttpRequest;
use IlluminateSupportFacadesAuth;
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
放入该函数中。
不幸的是,在这种情况下,浏览器无法找到订单功能。
你可以这么做
$organ_id = User::where('id',auth()->user()->id)->pluck('organ_id')->first();
if ($organ_id == 1) {
//code
}