【问题标题】:Different views based on user table information in Laravel 7Laravel 7 中基于用户表信息的不同视图
【发布时间】: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之外写任何东西(除了namespaceuse),那个if是不正确的,应该在方法test里面。还有那些functions,你想用postsorgans等做什么?您不创建 function 并返回函数...解释 100% 您想要实现的目标。用那个代码。另外,请阅读文档,因为不推荐这样做

标签: php laravel laravel-7


【解决方案1】:

你可以这样做

$organ_id = User::where('id',auth()->user()->id)->pluck('organ_id')->first();
    if ($organ_id == 1) {
      //code
    }

【讨论】:

    猜你喜欢
    • 2011-12-11
    • 2023-03-04
    • 2017-03-07
    • 1970-01-01
    • 1970-01-01
    • 2013-12-13
    • 1970-01-01
    • 2018-03-12
    • 2016-03-03
    相关资源
    最近更新 更多