Laravel Project
In this Laravel project tutorial we will learn to create Controller.
So far we have defined our request handling logic inside our routes which is fine. But it is a good practice to keep those logics in a separate file called Controllers and call them from routes.
For this project we will create a controller that will handle todo tasks.
I will keep both the routes and controller approach in the code so that you can refer it later. Here is my GitHub repository link for this project todo-laravel.
Alright, lets start building.
TodoController
Open terminal and run the following command to create a controller by the name TodoController
.
$ php artisan make:controller TodoController
Controller created successfully.
On success we will get a new controller file TodoController.php
inside the app/Http/Controllers
directory.
Open the file and you will get to see the following code.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class TodoController extends Controller
{
//
}
Create a new method inside the TodoController
class by the name getTodoById
. As the name suggest it will get us the todo task based on the provided id.
public function getTodoById($id)
{
//
}
At the top of the file include the following line use App\Todo
to use the Todo model.
Inside the getTodoById
method write the following code.
$todo = new Todo();
$result = $todo->find($id);
return $result;
At this moment our file will look like the following.
<?php
namespace App\Http\Controllers;
use App\Todo;
use Illuminate\Http\Request;
class TodoController extends Controller
{
public function getTodoById($id)
{
$todo = new Todo();
$result = $todo->find($id);
return $result;
}
}
Open routes/web.php
file and update the route that will return the detail of a specific task.
Route::get('/todo/{id}', 'TodoController@getTodoById');
Now, if we open the page 127.0.0.1:8000/todo/1
it will use the above route and will set {id}
to 1.
This route is wired to use the getTodoById
method of the TodoController
class. So, the route will call that method and will pass 1 as an argument to the method.
Inside the method we are fetching the todo task using the Todo model and returning it back.
Here is the output.
Note! You can ignore the two buttons "Raw|Parsed" at the top right. I have JSON Formatter installed on my Chrome browser and it helps to format JSON data.
So, our route and controller is working perfectly
In the next tutorial we are going to create an edit form that will help us to edit the todo tasks detail.
See you there. Have fun coding :-)
ADVERTISEMENT