Laravel 5 getting ID from URL

前端 未结 7 1762
一整个雨季
一整个雨季 2020-12-31 08:22

I have a table view in which I can click an button icon and redirect to another page carrying the id of the row that has been clicked.

@foreach ($pa         


        
相关标签:
7条回答
  • 2020-12-31 08:46

    The trick is to declare the url's structure at routes including the id, for example:

    // {{ URL::to('editpatient/'.$patient->pID) }}
    Route::get('editpatient/{patientId}', 'MyController@index');
    

    Then, just inject the id in the controller's function:

    public function index($patientId){
        // $patientId is the variable from url
    }
    
    0 讨论(0)
  • 2020-12-31 08:47

    Please refer to the answered question for how to get a parameter from a route. But if you stumbled on this old Laravel thread looking for how to retrieve a model by its ID, the simplest way is to instantiate the model in the controller's request parameter:

    Route::get('/retrieve_product/{product}', 'SearchController@getProduct');
    

    Then over in your controller, you simply need:

    use App\Product;
    
    class SearchController extends Controller
    {
        public function getProduct( Product $product ) {
            return $product;
        }
    }
    

    That's it. No find, no where, no get, no first etc.

    So, in this example, if you visit /retrieve_product/1 the first product is returned to you.

    0 讨论(0)
  • 2020-12-31 08:48

    This is late. But for the benefit of others like me;

    If you do not have to do it in a method like the answers above have shown, As of Laravel 5.0 (Not sure about previous versions), you can do

    $request->route('id');
    

    That returns the value of the id parameter on the route.

    0 讨论(0)
  • 2020-12-31 08:54

    Simple example:

    as link=>   example.com/user/1
    
    as rout=> Route::get('user/{id}', 'UserController@user');
    
    as UserController function 
    
    public function user($id){
    
        echo $id;
    
    }
    
    output => 1
    
    0 讨论(0)
  • 2020-12-31 08:58
    Route::get('post/user/{id}','ProductController@allpost')->where('id', '[0-9]+');
    

    Controller

    public function allpost($id)
        {
            $products = Product::where('uploadby', $id)->orderBy('created_at','desc')->paginate(5); <br>
            return view('product.user_product')->with('products', $products);
        }
    
    0 讨论(0)
  • 2020-12-31 09:04

    Or just use it within Blade: {{ request()->route('id') }}

    0 讨论(0)
提交回复
热议问题