通过Laravel中的链接href传递id

时间:2017-01-12 17:12:47

标签: php laravel parameters routes

是否可以通过Laravel中的链接href传递id并显示该页面,如/ projects / display / 2。

我有这个链接:

<td><a href="{{ url('projects/display', $projects->id) }}" class="btn btn-info">View</a></td>

将鼠标悬停在链接上时显示为/ projects / display / 2。但每当我点击链接时,我都会收到错误消息:

 Sorry, the page you are looking for could not be found.

我有一个名为projects / display的视图设置,以及路由和控制器。

路线:

<?php


Route::group(['middleware' => ['web']], function (){

    Route::get('/', 'PagesController@getIndex');

    Route::get('/login', 'PagesController@getLogin');

    Auth::routes();

    Route::get('/home', 'HomeController@index');

    Route::get('/projects/display', 'ProjectsController@getDisplay');

    Route::resource('projects', 'ProjectsController');


});

控制器:

<?php

namespace App\Http\Controllers;

use App\project;
use App\Http\Requests;
use Illuminate\Http\Request;
use Session;

class ProjectsController extends Controller
{

    public function index()
    {



    }


    public function create()
    {
        return view('projects.create');
    }



    public function store(Request $request)
    {
        $this->validate($request, array(

            'name' => 'required|max:200',
            'description' => 'required'
        ));

        $project = new project;

        $project->name = $request->name;
        $project->description = $request->description;

        $project->save();

         Session::flash('success', 'The project was successfully created!');

        return redirect()->route('projects.show', $project->id);


    }


    public function show()
    {
        $project = Project::all(); 

        return view('projects.show')->withProject($project);

    }


    public function edit($id)
    {
        //
    }


    public function update(Request $request, $id)
    {
        //
    }

    public function getDisplay($id){


        $project = Project::find($id);

        return view('projects/display')->withProject($project);

    }





}

3 个答案:

答案 0 :(得分:10)

您需要将路线更改为:

Route::get('/projects/display/{id}', 'ProjectsController@getDisplay');

然后使用:

生成网址
{{ url('projects/display/'.$projects->id) }}

答案 1 :(得分:1)

如果您按照以下方式编写路线,

Route::get('/projects/display/{projectId}', 'ProjectsController@getDisplay')->name('displayProject');

您可以在href中使用名称“ displayProject”,并将ID作为Array传递:

<td><a href="{{ route('displayProject', ['projects' => $projects->id]) }}" class="btn btn-info">View</a></td>

答案 2 :(得分:0)

您正在寻找的是参数化路线。在这里阅读更多相关信息: https://laravel.com/docs/5.3/routing#required-parameters