簡體   English   中英

Laravel 5.5將參數從控制器傳遞到資源

[英]Laravel 5.5 pass a parameter from a controller to a resource

我很難弄清楚如何將參數從控制器中的方法傳遞給資源。

在web.php中,我有以下路線:

Route::get('location/{id}','Controller@getLocation');

在控制器類中的方法下面:

public function getLocation($id){ 
    $result= //query
    return new LocationResource($result);
}

我想將$id從控制器傳遞到LocationResource。 我能怎么做? 謝謝

您做對了所有事情,只需執行查詢即可獲取對象:

$result = Location::find($id);

在資源中,您可以通過$this訪問該對象:

'id' => $this->id,

https://laravel.com/docs/5.5/eloquent-resources#resource-responses

你快到了。 您還應該添加一些安全檢查:

public function getLocation($id){ 
    if ($location = LocationResource::find($id)) {
        return $location;
    }
    abort(404, 'location ' . $id . ' not found');
}

這並不困難

在資源的第一個函數public function toArray($request)創建一個構造函數。 知道你可以使用$this->result

public function __construct($result)
{
    $this->result = $result;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM