【问题标题】:How can I append a user_id to the end of a URL in laravel?如何在 laravel 中将 user_id 附加到 URL 的末尾?
【发布时间】:2019-10-16 15:49:05
【问题描述】:

我正在为我的数据库中的每个用户创建一个记录日期/时间的报告表。这是我的控制器:

public function create()
{
    $user = auth()->user();

    return view('report.create', compact('user'));
}

public function show($id) 
{
    $data = Time::findOrFail($id);

    return view('report.show', compact('data'));  
}

所以现在如果我转到/reports/1,它只会让我访问 id 为 1 的时间数据。但是,我想要它,所以如果我转到 reports/1,我将可以访问 user_id 为 1 的用户的所有时间数据。

我尝试执行以下操作,但没有成功,并且在每个 /# 页面上都给了我一个 404。

public function show(Time $time) 
{
    $data= Time::findOrFail($time->user_id)

    return view('report.show', compact('data'));  
}

这是我的“报告”路线:

Route::resource('reports', 'ReportController');

这是我想要使用数据的时间数据库迁移:

Schema::create('times', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->unsignedBigInteger('user_id');
    $table->date('start_day');
    $table->text('category');
    $table->time('start_time');
    $table->time('finish_time');
    $table->time('duration');
    $table->text('notes');
    $table->timestamps();

    $table->foreign('user_id')->references('id')->on('users');
});

【问题讨论】:

    标签: php laravel eloquent controller routes


    【解决方案1】:

    你好,你只需要像这样修改显示控制器

    public function show($id) 
    {
        $data = Time::where('user_id',$id)->get();
    
        return view('report.show', compact('data'));  
    }
    

    【讨论】:

      【解决方案2】:

      您需要定义路由参数。您似乎也遇到了一些自动接线问题。

      Route::resource('reports/{id}', 'ReportController');
      

      【讨论】:

        【解决方案3】:

        改变

        $data= Time::findOrFail($time->user_id);
        

        $data= Time::where('user_id','=',$time->user_id)->get();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-05-27
          • 1970-01-01
          • 2017-07-10
          • 2015-03-13
          相关资源
          最近更新 更多