Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.4 Route with Request and Params

Tags:

php

laravel

I found myself stuck or lost in docs!

I'm using Laravel 5.4 and I'm trying to create validation in a controller which requires a request object.

My problem is my route passes parameters, I can't find in the docs an example how you include the Request $request argument and the $id parameter in a Controller method.

Here is my example:

1: SomeController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
...
public function edit($id) {
    $request = Request; // <-- Do I use that instead of passing an arg?
}

2: Routes with a Paramter in -- routes/web.php

Route::match(['GET', 'POST'], '/some/edit/{id}', 'SomeController@edit');

In their example @ https://laravel.com/docs/5.4/requests#accessing-the-request they have Request $request this in their controller, but what happens to Route parameters?:

public function store(Request $request) {}

Question: Do I need to edit the route or is the first parameter ignored if its a request?


A: Or would I do this in **SomeController.php?**

public function edit(Request $request, $id)
{
    // I would get the $request, but what happens to $id?
    $this->validate($request, [
        'title' => 'required|unique:posts|max:255',
    ]);
}

B: Perhaps, something like this?:

public function edit($id)
{
    // Or Request::getInstance()?
    $this->validate(Request, [
        'title' => 'required|unique:posts|max:255',
    ]);
}

Any advice would help, or even an example!

like image 732
JREAM Avatar asked Mar 02 '17 01:03

JREAM


1 Answers

Doing

public function edit(Request $request, $id)

should match the route you already have. So it's ok to do that. Request $request here is not a required parameter that you pass. Laravel will take care of it.

It works this way because everytime you send a request, well Laravel 'sends' a request for you (GET, POST). So, it always exist. But you can use use it within your controller if you dont pass it to the controller function as a parameter.

However, you can access it through the global helper function request() if you dont want to pass it as a function parameter.

$request = request();
$name = $request->name; // or 
$name = request('name');
like image 199
EddyTheDove Avatar answered Nov 04 '22 11:11

EddyTheDove