如何在 Laravel 中传递 URL 中的值

How to pass value in URL in Laravel

我想点击 "View Detail" 按钮并转到另一个页面“/viewdeail/id=2”,这里的 id=2 来自“查看详细信息”按钮点击。到目前为止,我准备了这个片段。

控制器:

public function schooldetailviewid($school_id)
     {
        return view('viewdeail/school_id={$school_id}', compact('school_id'));
     }

路线

Route::get('/viewdeail/school_id={school_id}', 'ViewController@schooldetailviewid')->name('schooldetail');

我很困惑如何解决这个问题。

如果您以这种方式传递参数/viewdeail?id=2

然后在您的控制器中,您需要使用 Request 对象来获取它:

public function schooldetailviewid(Request $request)
{ 

    $school_id = $request->get('id');

    return view("viewdeatil/school_id=$school_id", compact('school_id'));
}

请查看 Laravel 路由文档:https://laravel.com/docs/5.8/routing#route-parameters

使用Laravel,如果你需要在你的路由中传递一个必需的参数,你需要在你的routes/web.php文件中指定它,并从你的控制器动作中获取它。

这是常见的方法:

// routes/web.php

Route::get('/viewdeail/{schoolId}', 'ViewController@details')->name('schooldetail');
// app/Http/Controllers/ViewController.php

class ViewController extends Controller {

    ...

    public function details($schoolId) {
        // your view located in ressources/views folder
        return view('viewdeail/', compact('schoolId'));
    }

}

现在,如果你只想获取像domain.tld/viewdeail?schoolId=3这样的参数,你需要删除routes/web.php文件中先前定义的路由中的{schoolId},并编辑你的控制器然后像这样继续:

// app/Http/Controllers/ViewController.php

use Illuminate\Http\Request; // we need the Request class, so import it

class ViewController extends Controller {

    ...

    public function details(Request $request) {
        $schoolId = $request->query('schoolId');

        // your view located in ressources/views folder
        return view('viewdeail/', compact('schoolId'));
    }

}

您可以通过多种方式实现这一目标。

你可以,

$school_id = $request->get('id');

$school_id = YourModel::find('$id');

您可以使用请求来获取您的数据

控制器

public function schooldetailviewid(Request $request)
{ 

$school_id = $request->get('id');

return view("viewdeatil/school_id/$school_id", compact('school_id'));
}

路线

你的路线应该是这样的;

Route::get('/viewdeail/school_id/{school_id}', 'ViewController@schooldetailviewid')->name('schooldetail');

Blade 你的 a 标签应该是这样的;

<a href="{{route('schooldetail', $school_id->id)}}">getDetails</a>
 Route::group(['as'=>'admin.','prefix'=>'admin','namespace'=>'Admin','middleware'=>['auth','admin']], function (){

    Route::resource('category','CategoryController');

}); 

public function index()
    {
        $categories = Category::latest()->get();
        return view('admin.category.index',compact('categories'));
    }