Dynamic Data Handling: URL Arguments in Laravel Controllers
id
.If you haven’t created the TestController, it’s time to do so now. I’m going to be using the one from the previous article, but the artisan
command to create it is: php artisan make:controller TestController
.
Creating the Route
Our first task is to create the route. The URL will contain a parameter that will be passed to the Controller’s method.
<?php
use App\Http\Controllers\TestController;
Route::get('/test-controller/id/{id}', [TestController::class, 'edit']);
We don’t have to explicitly state that we’re sending the {id}
argument to the edit
method in the TestController
within our route file.
Accepting the Argument
Accepting the argument in the TestController
is as simple as defining the $id
parameter in our edit
method.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class TestController extends Controller
{
// ...
public function edit($id)
{
return "If we were editing, this would be for " . $id;
}
}
We can now visit our routehttp://0.0.0.0/test-controller/edit/3
and see the results, which will display If we were editing, this would be for 3
.
Multiple Arguments
It’s pretty self explanatory, but you can pass multiple arguments. Just make sure that they’re defined in order that you pass them inside of your route.
<?php
Route::get('/test-controller/delete/{id}/name/{name}', [TestController::class, 'delete']);
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class TestController extends Controller
{
// ...
public function delete($id, $name)
{
return "Record " . $id . " has been deleted for " . $name;
}
}
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class TestController extends Controller
{
// ...
public function delete($user_id, $user_name)
{
return "Record " . $user_id . " has been deleted for " . $user_name;
}
}
I don’t recommend it, but it does work. I normally like to keep it consistent and match the URL parameter with the method parameter.
Next time, we’ll look at Single Action Controllers. See you then.
Laravel Series
Continue your Laravel Learning.
Navigating Laravel: An Introduction to Controller
Laravel – P24: Controllers Intro
Begin your journey with Laravel controllers to manage app logic & data flow. Discover tips for effective MVC architecture integration.
Dynamic Data Handling: URL Arguments in Laravel Controllers
Laravel – P25: URL Arguments To Controllers
Learn to pass URL arguments to Laravel controllers for dynamic content delivery. Enhance user interaction with tailored responses.
Simplifying Laravel: The Power of Single Action Controllers
Laravel – P26: Single Action Controllers
Optimize your Laravel application with single action controllers for focused functionality. Streamline tasks for efficiency & clarity.