Starting with Laravel – Routes and Views


Now that we have made the basic Model of our ToDos, it would be good to visualize them. But where and how should we tell the application what we want displayed? To tell the application how it should behave when it receives a request through an HTTP request, we should use Routes.

As you might have already guessed, you can find a file named routes.php in the app folder of your project. It will contain a singe preset route for the main route:

<?php
Route::get('/', function() {
    return View::make('hello');
});

What it means is that when an user visits the URL http://localhost/your-project-name/public/ an anonymous function is called that will return the view named ‘hello’.

If we want to make a view that will show all ToDos, then we have to first define the route and then the view itself. To do so, we can add a route with the following:

Route::get('/tasks', function() {
    return View::make('tasks');
});

If we visit the URL http://localhost/your-project-name/public/tasks, it will give us the following error

InvalidArgumentException
View [tasks] not found.

which is absolutely correct, because Laravel cannot find the view that we want to show.

What we need to do is create this view.  To make things easier, we can use the built-in template engine of Laravel. To be able to use it, we have to give our file name like “tasks.blade.php”, where “tasks” is the name of our view. We have to create this file in app/views with the following content:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Tasks</title>
    </head>
    <body>
        @foreach (Task::all() as $task)
        <div>
            You have to {{{ $task-&gt;description }}}
        </div>
        @endforeach
    </body>
</html>

As you can notice, we have the methods “@foreach” and “@endforeach”, which point to the beginning and end of foreach statement. This is the way Laravel’s Blade template know what to do. We do not need to add php tags. The method “Task::all()” calls a method from the Task model, which loads all tasks. For each single task we create a <div> element and to render the task’s content we add three curly braces and access the description of the task with $task->description. That is all we need to visualize all the tasks. We can refresh the page at  http://localhost/your-project-name/public/tasks to see all tasks from the database.

In the next tutorials we will see how to send data to the view through the route, how to use controllers instead of doing everything in the routes file and how to add a form to create new tasks.

Previous articles about Laravel:

  1. Starting with Laravel – Installation
  2. Starting with Laravel – Migrations and Seeding

Next article: Starting with Laravel – Controllers