70

Creating a Basic ToDo Application in Laravel 5 – Part 2

Posted February 5th, 2015 (Updated 9 Feb 2015) in PHP

Welcome back to my simple to-do application tutorial for Laravel 5. This tutorial is relatively long so I’ve broken it up into multiple posts.

  1. Part 1 – Installation, Database and Routes
  2. Part 2 – Listing Projects and Tasks
  3. Part 3 – Create/Edit/Delete
  4. Part 4 – Validation

The source for each part can also be found on GitHub.

So far we have a working database complete with seed data and a bunch of routes for displaying, editing and deleting our projects and tasks. In this second chapter I’ll cover controllers, models (with relationships), views (including the blade templating language and layouts) and route model binding.

 

Laravel Form Helpers

In Laravel 4 we had a HTML package but it was removed for 5 to cut down on cruft. Add it back in by following the instructions in my How to Install Illuminate/HTML In Laravel 5 tutorial. In addition to HTML and Form facades, this package provides some handy helper functions such as link_to_route() which we’ll be using later.

 

Controllers and Blade View Layouts

Further details: See Resourceful Controllers Part 1 and Part 2, Blade 101

If you browse to /projects you’ll get an empty page. Why is that? Well let’s find out. Run php artisan route:list one more time and look at this line:

1
2
3
4
5
+--------+----------+----------------------------------------+------------------------+-------------------------------------------------+------------+
| Domain | Method   | URI                                    | Name                   | Action                                          | Middleware |
+--------+----------+----------------------------------------+------------------------+-------------------------------------------------+------------+
|        | GET|HEAD | projects                               | projects.index         | App\Http\Controllers\ProjectsController@index   |            |+--------+----------+----------------------------------------+------------------------+-------------------------------------------------+------------+

Looks like the /projects URL is loading ProjectsController’s index method. So open up /app/Http/controllers/ProjectsController.php and update the method to point to a view we’ll create:

1
2
3
4
public function index()
{
	return view('projects.index');}

We’re using Blade Templates in this tutorial so create a /resources/views/projects/index.blade.php file and enter some text in there. Hit /projects in your browser again. If everything is working correctly you should see the text you entered above. Do the same for the create controller method.

Showing the contents of a view is great, but if we have more than one page on our site we’ll want a consistent template across all pages. In other words, we need the view’s contents to sit inside a basic HTML template. This is done with controller layouts.

There are a few steps to implementing controller layouts:

  1. Create a layout view. Laravel actually ships with a pretty decent one called app.blade.php so we’ll save some time and just use that. Notice near the bottom the layout contains a @yield(‘content’) line. That’s the function that will load our actual content.
  2. Reference your layout in your view using @extends(‘app’) and wrap in a @section(‘content’) block like so:
    1
    2
    3
    4
    5
    
    @extends('app')
     
    @section('content')
        This is my /resources/views/projects/index.blade.php file!
    @endsection

In /resources/views/projects folder create a show.blade.php, index.blade.php and create.blade.php view with the above markup replacing the filename as necessary. With these in place, refresh /projects in your browser. You should now see the app.blade.php skeleton around your view contents.

Route Model Binding

Further Details: If you’re a laracasts member see Route Model Binding

By default Laravel will provide an ID value to various resourceful controller methods such as show(), edit(), update() and destroy(). This is fine but it adds alot of extra boilerplate we need to write – grabbing the model instance, checking if it exists etc. Thankfully Laravel provides something called route model binding that helps with this issue. Instead of providing an $id variable, the method will be given the $project or $task object instance instead.

Open up /app/Http/routes.php and add the following two lines:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Provide controller methods with object instead of ID
Route::model('tasks', 'Task');Route::model('projects', 'Project'); 
// Use slugs rather than IDs in URLs
Route::bind('tasks', function($value, $route) {
	return App\Task::whereSlug($value)->first();
});
Route::bind('projects', function($value, $route) {
	return App\Project::whereSlug($value)->first();
});
 
Route::resource('projects', 'ProjectsController');
Route::resource('projects.tasks', 'TasksController');

and in your TasksController and ProjectsController replace every method definition’s $id reference with Task $task and Project $project like so:

// public function edit($id)
public function edit(Project $project)

At this point you can also pass the object to its respective view in each controllers show, edit and update methods like so as we’ll be using them later:

1
2
3
4
public function edit(Project $project)
{
    return view('projects.show', compact('project'));}

The TasksController will also need some minor modifications. Because we’re using nested resources, php artisan route:list will tell us that task routes all include a {projects} mask in addition to the {tasks} mask that some of them receive. As a result the controller methods will be passed a Project instance as their first argument. So update them accordingly remembering to update method docs and pass the new $project variable.

By this point your controllers should look like so:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
// /app/Http/Controllers/ProjectsController.php
<?php namespace App\Http\Controllers;
 
use App\Project;
use App\Http\Requests;
use App\Http\Controllers\Controller;
 
use Illuminate\Http\Request;
 
class ProjectsController extends Controller {
 
	/**
	 * Display a listing of the resource.
	 *
	 * @return Response
	 */
	public function index()
	{
		$projects = Project::all();
		return view('projects.index', compact('projects'));
	}
 
	/**
	 * Show the form for creating a new resource.
	 *
	 * @return Response
	 */
	public function create()
	{
		return view('projects.create');
	}
 
	/**
	 * Store a newly created resource in storage.
	 *
	 * @return Response
	 */
	public function store()
	{
		//
	}
 
	/**
	 * Display the specified resource.
	 *
	 * @param  \App\Project $project
	 * @return Response
	 */
	public function show(Project $project)
	{
		return view('projects.show', compact('project'));
	}
 
	/**
	 * Show the form for editing the specified resource.
	 *
	 * @param  \App\Project $project
	 * @return Response
	 */
	public function edit(Project $project)
	{
		return view('projects.edit', compact('project'));
	}
 
	/**
	 * Update the specified resource in storage.
	 *
	 * @param  \App\Project $project
	 * @return Response
	 */
	public function update(Project $project)
	{
		//
	}
 
	/**
	 * Remove the specified resource from storage.
	 *
	 * @param  \App\Project $project
	 * @return Response
	 */
	public function destroy(Project $project)
	{
		//
	}
 
}
 
 
// /app/Http/Controllers/TasksController.php
<?php namespace App\Http\Controllers;
 
use App\Project;
use App\Task;
use App\Http\Requests;
use App\Http\Controllers\Controller;
 
use Illuminate\Http\Request;
 
class TasksController extends Controller {
 
	/**
	 * Display a listing of the resource.
	 *
	 * @param  \App\Project $project
	 * @return Response
	 */
	public function index(Project $project)
	{
		return view('tasks.index', compact('project'));
	}
 
	/**
	 * Show the form for creating a new resource.
	 *
	 * @param  \App\Project $project
	 * @return Response
	 */
	public function create(Project $project)
	{
		return view('tasks.create', compact('project'));
	}
 
	/**
	 * Store a newly created resource in storage.
	 *
	 * @param  \App\Project $project
	 * @return Response
	 */
	public function store(Project $project)
	{
		//
	}
 
	/**
	 * Display the specified resource.
	 *
	 * @param  \App\Project $project
	 * @param  \App\Task    $task
	 * @return Response
	 */
	public function show(Project $project, Task $task)
	{
		return view('tasks.show', compact('project', 'task'));
	}
 
	/**
	 * Show the form for editing the specified resource.
	 *
	 * @param  \App\Project $project
	 * @param  \App\Task    $task
	 * @return Response
	 */
	public function edit(Project $project, Task $task)
	{
		return view('tasks.edit', compact('project', 'task'));
	}
 
	/**
	 * Update the specified resource in storage.
	 *
	 * @param  \App\Project $project
	 * @param  \App\Task    $task
	 * @return Response
	 */
	public function update(Project $project, Task $task)
	{
		//
	}
 
	/**
	 * Remove the specified resource from storage.
	 *
	 * @param  \App\Project $project
	 * @param  \App\Task    $task
	 * @return Response
	 */
	public function destroy(Project $project, Task $task)
	{
		//
	}
 
}

If you refresh the url /projects/project-1 everything should still be working.

 

Displaying Our Models

Project listing page

It’s time to start listing our projects and tasks. Open /projects in your browser. Based on php artisan route:list this is our project listing page. Open /resources/views/projects/index.blade.php and set it to the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@extends('app')
 
@section('content')
    <h2>Projects</h2>
     @if ( !$projects->count() )
        You have no projects
    @else
        <ul>
            @foreach( $projects as $project )
                <li><a href="{{ route('projects.show', $project->slug) }}">{{ $project->name }}</a></li>
            @endforeach
        </ul>
    @endif
@endsection

There are a few things going on above:

  1. I’m using the blade templating language’s if and foreach control-flow functions as well as its print function (the double curly braces).
  2. I’m checking if there are any projects to show. If not, display a message saying so. If there are, list them all
  3. I’m calling the route() helper with a named route (You can see a list of your named routes with php artisan route:list) to link to each projects details page.

You’ll also need to pass the $projects variable to this view or you’ll get an undefined variable error. Open /app/Http/controllers/ProjectsController.php and update the index() method to:

1
2
3
4
5
public function index()
{
	$projects = Project::all();	return view('projects.index', compact('projects'));}

Refresh and you’ll now see a listing of your projects.

 

Model Relations – The Project Details page

Further Details: See Eloquent Relationships

On the project details page we need to display a list of the given projects tasks. To do that we need to define a one-to-many relationship in our Project model allowing it to grab its tasks.

Open /app/Project.php and add a tasks() method like so:

1
2
3
4
public function tasks()
{
	return $this->hasMany('App\Task');
}

Inversely we can also add a many-to-one relationship to our Task model:

1
2
3
4
public function project()
{
	return $this->belongsTo('App\Project');
}

To make sure it worked:

$ php artisan tinker
>App\Project::whereSlug('project-1')->first()->tasks->count();
5
>App\Project::whereSlug('project-2')->first()->tasks->count();
2
>App\Task::first()->project->name;
Project 1

Perfect! The view can now be updated (/resources/views/projects/show.blade.php):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@extends('app')
 
@section('content')
    <h2>{{ $project->name }}</h2>
     @if ( !$project->tasks->count() )
        Your project has no tasks.
    @else
        <ul>
            @foreach( $project->tasks as $task )
                <li><a href="{{ route('projects.tasks.show', [$project->slug, $task->slug]) }}">{{ $task->name }}</a></li>
            @endforeach
        </ul>
    @endif
@endsection

Click a project on the project listing page in your browser and your project will now display complete with its task listing.

Finally we have the task show page (/resources/views/tasks/show.blade.php). This one is very straightforward:

1
2
3
4
5
6
7
8
9
10
@extends('app')
 
@section('content')
    <h2>
        {!! link_to_route('projects.show', $project->name, [$project->slug]) !!} -
        {{ $task->name }}
    </h2>
 
    {{ $task->description }}
@endsection

Note: Be very careful when using model relationships. It’s easy to generate huge numbers of SQL queries if you’re not careful. This is called the N+1 problem. See the video below for details on what exactly the N+1 problem is, and how to protect against it.

 

Conclusion

Today we covered:

  • Route Model Binding
  • Models (with one-to-many relationships)
  • Controllers (with route model binding)
  • Views (with blade templating language and layouts)

We now have a working listing of projects and tasks. In the next lesson we’ll concentrate on editing, creating and deleting projects and tasks. Stay tuned!

  • Steve Tredinnick

    Hi… to use the link_to_route function in /resources/views/tasks/show.blade.php at the end of the post you need to have installed the Illuminate/Html Service provider, this is not listed until the next part of the tutorial.

    • flynsarmy

      Thanks. Moved from part 3 to here.

      • http://mataperros.wordpress.com/ Cibermesías

        I can’t find it

  • Joonas Lieppinen

    I have a problem with routing to the tasks. It shows me a page

    Whoops, looks like something went wrong. when I try to see the individual tasks. I had this problem in the end of chapter 2.

    My routes.php

    Route::get(‘/’, ‘WelcomeController@index’);

    Route::get(‘home’, ‘HomeController@index’);

    Route::controllers([
    ‘auth’ => ‘AuthAuthController’,
    ‘password’ => ‘AuthPasswordController’,
    ]);

    Route::model(‘tasks’, ‘Task’);
    Route::model(‘projects’, ‘Project’);

    Route::bind(‘tasks’, function($value, $route) {
    return AppTask::whereSlug($value)->first();
    });

    Route::bind(‘projects’, function($value, $route) {
    return AppProject::whereSlug($value)->first();
    });

    Route::resource(‘projects’, ‘ProjectsController’);
    // Route::resource(‘tasks’, ‘TasksController’);
    Route::resource(‘projects.tasks’, ‘TasksController’);

    • flynsarmy

      You’ll need to provide a better error message. Maybe check the /storage/logs directory or ensure app_debug is turned on.

  • flynsarmy

    As per above, your ProjectsController show method should look like:


    public function show(Project $project)
    {
    return view('projects.show', compact('project'));
    }

    and your /resources/views/projects/show.blade.php should look like:


    @extends('app')
    @section('content')
    {{ $project->name }}
    @if ( !$project->tasks->count() )
    Your project has no tasks.
    @else

    @foreach( $project->tasks as $task )
    slug, $task->slug]) }}">{{ $task->name }}
    @endforeach

    @endif
    @endsection

    • Joonas Lieppinen

      Got it working with that! thanks! The link_to_route() function was not working for me even though I had IlluminateHtml installed.

      • eugenevdm

        How did you fix link_to_route? I am getting Call to undefined function link_to_route() even though I also have IlluminateHtml installed as well. I can confirm it’s installed because I follow the tutorial how to install and the ‘artisan tinker’ command works with a sample form.

  • Reggie Niccolo Santos

    Hi,

    I am experiencing an error when trying out the model relations part:

    PHP Fatal error: Call to a member function count() on a non-object in /Applications/XAMPP/xamppfiles/htdocs/l5todo/vendor/psy/psysh/src/Psy/ExecutionLoop/Loop.php(67) : eval()’d code on line 1

    Here are my models:

    Project.php:

    hasMany(‘AppTask’);

    }

    }

    Task.php:

    belongsTo(‘AppProject’);

    }

    }

    Would you know why I am experiencing this error and how can I fix it? Thanks!

  • Afreen

    why here used slug?

  • edwin

    As I try to access / projects gives me a 404 error not found…

    my routes.php

    Route::get(‘/’, ‘WelcomeController@index’);

    /*Route::get(‘home’, ‘HomeController@index’);

    Route::controllers([
    ‘auth’ => ‘AuthAuthController’,
    ‘password’ => ‘AuthPasswordController’,
    ]);
    */
    Route::bind(‘tasks’, function($value, $route) {
    return AppTask::whereSlug($value)->first();
    });
    Route::bind(‘projects’, function($value, $route) {
    return AppProject::whereSlug($value)->first();
    });

    Route::resource(‘projects’, ‘ProjectsController’);
    //Route::resource(‘tasks’, ‘TasksController’);
    Route::resource(‘projects.tasks’, ‘TasksController’);

    • flynsarmy

      Sounds like you don’t have mod redirect enabled.

      • balakumar

        could you help me to enable the mod redirect?

        • flynsarmy

          That’s something Google should be able to help with. Too detailed for me to get into.

          • balakumar

            Even after mod redirect I am having the same problem(404page for this url /projects)? How to recover this?

    • balakumar

      Have you got the solution?Because I too experience the same problem.give me the solution if you got?

  • shivani

    hi..i am getting this error when i run ..
    local.ERROR: exception ‘ReflectionException’ with message ‘Class AppHttpControllersProject does not exist’

    • flynsarmy

      Sounds like you set up your routes.php wrong. It should look like this.

      • Ay

        I have the same problem. I have crosschecked but the error persisted. I also included what @gauravgoyal:disqus wrote.
        I traced my app and it seems it’s not getting my Model

      • arno

        I had the same error as @shivani and following gauravgoyal’s comment I noticed I overlooked lines 93 and 94 (in this part, under ‘By this point your controllers should look like so:’).

        Nice tutorial so far…! Thanks

    • gauravgoyal

      Probably you are missing the following line in your TasksController.php:

      use AppProject;

    • Aristosoft

      Hello @shivani, had the same problem….have troubleshooted it for a long time….no solution yet. Have you able to solve it

      • flynsarmy

        Wow you guys. Did you check the git repo? All you need to do is make sure your code is the same as the git repo (which is the same as my post). You’re obviously missing steps.

  • burnzzz

    and don´t forget that a normal “chmod 777 storage” is not enough for laravel 5. You need to do “chmod -R 777 storage” so all the subfolders can be written to as well.

    this took me an hour, because I could not load any self defined blade views.
    Always got “Internal Server Error 500″ …

  • Ennosuke

    i got an error in the tinker :

    >>> AppTask::first()->project->name;
    PHP error: Trying to get property of non-object on line 1

    already added the project() function in the Task model :

    return $this->belongsTo(‘AppProject’);

    • flynsarmy

      Make sure your task in the db has a valid project_id. And make sure a corrosponding row in the projects table exists.

      • Francesco Pagnanelli

        Hello,
        I have the same error too,
        all rows in the database are valid, but when i run
        AppTask::first()->project->name;

        i have the error :
        Trying to get property of non-object on line 1

        • Pavlo Gagin

          that’s because your are trying to reach an Object from the Collection without specifying that Object – Collection Task hasMany Project, right?

          class Project extends Model {
          . . .
          public function task()
          {
          return $this->belongsTo('AppTask');
          }
          }
          and
          class Task extends Model {
          . . .
          public function project()
          {
          return $this->hasMany('AppProject');
          }
          }

          So, basically thisAppTask::first()->project;gives you a Collection of Projects and you have to specify which Project do you want, in tinkerAppTask::first()->project->first()->name;

          • Janakiraman

            I tried the above but still getting the error like this Fatal error: Call to a member function first() on a non-object

            • http://www.sharkweb.net Pavlo Gagin

              Ok… using previous Model’s relationship try this (tinker):

              $task = AppTask::findOrFail(1)->project;
              as result you may get either Collection of projects or error message: ‘No query results for model [AppTask].’

              P.S. double check every function in the each Model and make sure that you have data in Database … and connection to it

      • CreativePerson

        I’ve made sure of that, but in Tinker, this:

        AppTask::first()->project->name;

        results in the following error message:

        LogicException with message ‘Relationship method must return an object of type IlluminateDatabaseEloquentRelationsRelation’

        My Projects.php file consists of this:

        hasMany(‘AppTask’);
        }
        }

        What am I doing wrong?

        • CreativePerson

          I solved this problem by typing the following in succession in Tinker:

          AppTask::first()
          AppTask::first()->project_id;
          AppTask::first()->project;
          AppTask::first()->project->name;

          Each of these worked. I don’t think I changed any code in the files. I can’t imagine why the final line didn’t work before, yet it worked after I typed the first 3 lines. So I’m completely puzzled.

          Anyway, everything works now. I hope this helps anyone having trouble.

  • gekcrab

    why my blade coding template are display in browser?

  • http://mataperros.wordpress.com/ Cibermesías

    I got an error in the last part: “link_to_route function undefined”.

    I had to change {!! link_to_route(‘projects.show’, $project->name, [$project->slug]) !!} to {{ route(‘projects.show’, [$project->slug]) }}

    • flynsarmy

      You need to install illuminate/html. It’s the very first step on this page.

      • eugenevdm

        I’m really struggling with this, 18 hours already. I notice that link_to_route / Illuminate is now also rather be found in collective. http://laravel.io/forum/02-04-2015-laravel-5-error-link-to-route

        • flynsarmy

          So add “LaravelCollective/html”:”5.0.*” – it shouldn’t be complicated. Just make sure you’ve added the service provider to your config file or the package won’t get loaded.

          • eugenevdm

            Thanks man, after having spent all that time and finally getting it working, that:

            1. My problem was the composer require command and trying to use it in PhpStorm.

            2. PhpStorm default for doing composer command is the root of the folder, not the application folder. I kept on updating the wrong .json file until I CD to correct folder. The menu in PhpStorm also seemed to update the incorrect .json file.

            3. Even when it properly updated it, PhpStorm didn’t update my remote development server so I have to guess which folder to upload.

            It’s working perfectly now. It’s a really great demo. I’ve extended it to be three levels deep, i.e. Projects/Lists/Tasks.

            Thank you so much for putting me on the fast track with Laravel 5. I haven’t been this inspired in a very long time.

  • ForFin

    Hi, I got an error when trying to request http://localhost/laravel/public/projects

    here is my log:

    [2015-03-28 09:16:56] production.ERROR: exception ‘SymfonyComponentDebugExceptionFatalErrorException’ with message ‘Class ‘AppHttpControllersProject’ not found’ in C:xampphtdocslaravelappHttpControllersProjectsController.php:17

    Stack trace:

    #0 {main}

    • Fabian Manzano

      Hi were you able to fix this issue?
      I am having the same error,not sure what I did wrong

      • Vladimir

        use AppProject; is appearing in the head’s second version of controller class file -)

  • http://seocrust.com/ Sagar Guhe

    Hi I am getting:

    Route [projects.tasks.show] not defined. (View: /home/sagar/myfirstapp_laravel/resources/views/Projects/show.blade.php)

    I have view/Projects and view/Tasks folder

    • flynsarmy

      Those folders should be lowercase.

    • GG

      I had the same issue, but for a different reason. In show.blade.php projects.tasks.show s/b just “project”, so project.tasks.show.

      Edit: disregard, I had it wrong in routes.php.

    • NMSAN

      Did you solve this problem.. I am getting it too.. :(

  • Ireco Gnizedyou

    Getting 404 code on /projects/project-1 while /projects/1 is working. I have checked/compared the routes and controllers and everything seems correct. Any idea why url with slug causes the error? Thanks

    • Ireco Gnizedyou

      I have added full namespace path to controllers in route resources and only after got worked URL with slug:

      Route::resource(‘projects’, ‘AppHttpControllersProjectsController’);

      Route::resource(‘projects.tasks’, ‘AppHttpControllersTasksController’);

    • Kilowat

      Looking here app/http/roures.php, you must have code something:
      Route::bind(‘project’,function($value)
      {
      return Project::whereSlug($value)->first();
      });

  • Sanket Sharma

    Call to undefined function link_to_route() getting this error on http://localhost/path_to_app/public/projects/project-1/tasks/task-2 this page

    • flynsarmy

      You didn’t follow the very first step of this tutorial nor did you read the numerous comments with the exact same issue as you and my response to them.

      • Sanket Sharma

        Yeah.. I skipped IlluminateHTML package.. Thanks its working now…

  • DaveW

    I’m at the of Route Model Binding and get the following error message : FatalErrorException in ProjectsController.php line 18:
    Class ‘AppProject’ not found

    • flynsarmy

      Does this file exist and have its namespace set correctly? Are you in routes.php or some other file? If it’s some other file, you need to add use AppProject; to the top.

      • Charles Vlug

        i olso get “Class ‘AppProject’ not found”, even with “use AppProject;” in the controller.
        But only if i omit:

        // Use slugs rather than IDs in URLs
        Route::bind(‘tasks’, function($value, $route) {
        return AppTask::whereSlug($value)->first();
        });
        Route::bind(‘projects’, function($value, $route) {
        return AppProject::whereSlug($value)->first();
        });”
        How can i get it working without the slugs?

        adding “$router->model(‘Project’, ‘AppProject’);” to RouteServiceProvider::boot makes no difference.

        • flynsarmy

          Go to the git repo (linked to at the top of this post), check your model, controller and routes files and make sure yours are the same as mine.

          • Charles Vlug

            Thanks. Most people don’t want to make a todo list however, but use you tutorial as a blueprint for an other application. If that application is not using slugs, it would be essential to know how to use Route Model Binding wihout slugs.

  • Guest

    The page loads when I click on a task from a project, but the task name and task description in the tasks/show.blade.php don’t show up on the page. Only the Project link is displayed. Does anyone know why this is?

    in tasks/show.blade.php, I have…

    @extends(‘app’)

    @section(‘content’)

    {!! link_to_route(‘projects.show’, $project->name, [$project->slug]) !!} –
    {{ $task->name }}

    {{ $task->description }}
    @endsection

    …just like how it is in the tutorial

  • Bala Kumar

    i am running this project in virtual host when I run the url(http://mysite.local/projects), it shows me a 404 error page.How can I recover this?

    • Dioude

      if you’re using Apache, don’t forget to enable rewrite_module :)

    • francesco filippi

      Did you start the server?

      – Open up your terminal and CD to your project’s directory

      – Type ‘php artisan serve’, you should get something like ‘Laravel development server started on http://localhost:8000/

      – Hit http://localhost:8000/projects in your browser

  • balakumar

    shows 404 error while running the url(‘http://mysite.local/projects’). It is in virtual host

  • balakumar

    Log shows the following, can anyone help me to solve this,

    #35 C:wampwwwlaravelpublicindex.php(53): IlluminateFoundationHttpKernel->handle(Object(IlluminateHttpRequest))

    • flynsarmy

      Can’t tell anything from that. Can you paste the rest of the dump plz.

      • balakumar

        [2015-04-29 07:14:09] production.ERROR: exception ‘SymfonyComponentDebugExceptionFatalErrorException’ with message ‘Namespace declaration statement has to be the very first statement in the script’ in C:wampwwwlaravelappHttpControllersProjectsController.php:2

        Stack trace:

        #0 C:wampwwwlaravelstorageframeworkcompiled.php(1736): IlluminateFoundationBootstrapHandleExceptions->fatalExceptionFromError(Array)

        #1 [internal function]: IlluminateFoundationBootstrapHandleExceptions->handleShutdown()

        #2 {main}

  • balakumar

    can I have the final models of Project and Task

    • flynsarmy

      Look at the git repo mentioned at the top of this and all other posts in this series.

  • CreativePerson

    For me, the following section of the tutorial is not clear. My questions are in [square brackets]. Here’s the problematic section of the tutorial:

    “There are a few steps to implementing controller layouts:

    Create a layout view. [ Where? You mean in resources/views? ] Laravel actually ships with a pretty decent one called app.blade.php [No such file exists in my project.] so we’ll save some time and just use that. Notice near the bottom the layout contains a @yield(‘content’) line. That’s the function that will load our actual content.

    Reference your layout [ Which layout? ] in your view [ You mean in resources/views/app.blade.php ? ] using @extends(‘app’) and wrap in a @section(‘content’) block like so:

    @extends(‘app’)

    @section(‘content’)
    This is my /resources/views/projects/index.blade.php file!
    @endsection

    [ Are the above 4 lines the entire contents of resources/views/app.blade.php ? If there is more, can you please show it? ]

    In /resources/views/projects folder create a show.blade.php, index.blade.phpand create.blade.php view with the above markup replacing the filename as necessary. With these in place, refresh /projects in your browser. You should now see the app.blade.php skeleton around your view contents. ”

    [ After trying to follow these steps, my content has disappeared entirely. ]

    • flynsarmy

      I think one look at the git repo linked to at the top of this article would answer all your questions. A lot of your issues probably stem from you using Laravel 5.1 whereas this article was written back when 5.0 was the latest version and those files were available. In 5.1 some directories were changed and it looks like app.blade.php was replaced with welcome.blade.php.

      Now for your questions one by one:

      [ Where? You mean in resources/views? ]

      Yep. That’s where views go. I like to make ‘Layout’ views which is the HTML skeleton around ‘Page’ views – ie the About page content and any relevant markup. And ‘Partial’ views that are called from Layout and Page – ie a ‘header’ partial or a ‘footer’ partial – just to split things up into more workable pieces.

      [No such file exists in my project.]

      Was a laravel 5.0 thing. See above. It’s still available in my git repo.

      [ Which layout? ]
      [ You mean in resources/views/app.blade.php ? ]
      Any layout you want. It’s your project. In mine I used app.blade.php.

      [ Are the above 4 lines the entire contents of resources/views/app.blade.php ? If there is more, can you please show it? ]

      The git repo is linked to at the start of EVERY tutorial in this series. Go there. It has the full file.

      [ After trying to follow these steps, my content has disappeared entirely. ]

      Sounds like you need to do some debugging. View your logs. It’ll tell you what you’ve done wrong. Also make sure the debug config option is turned on.

      I may go through the 4 posts and update them for L5.1 however these things are very time consuming to write and as I’m doing it for free, other stuff often takes priority.

  • Oli

    I have en error “View [projects.index] not found.”

    my ProjectsController class :

    public function index()
    {
    return view(‘projects.index’);
    }

    And the file resources/views/projects/index.blade.php is OK (with the right permissions) :
    @extends(‘l5todo’)

    @section(‘content’)
    This is my /resources/views/projects/index.blade.php file!
    @endsection

    Usin tinker :
    php artisan tinker
    Psy Shell v0.4.4 (PHP 5.6.10 — cli) by Justin Hileman
    >>> view()->exists(‘l5todo’);
    => true
    >>> view()->exists(‘errors.503′);
    => true
    >>> view()->exists(‘projects.index’);
    => false

    Any suggestions ?