CSCI 445 - Laravel

This document includes information related to the use of Laraval, including:

LaraCasts

We will make extensive use of LaraCasts this semester. The following are free videos related to setup:

Laravel installation

Some resources you may find valuable (note that I am not using the VM/Homestead, so didn't need the third link... but you may find it useful):

Assuming you already have PHP installed (e.g., via XAMPP, WampServer, etc.), installing laravel is fairly straightforward.

The first step is to install composer (dependency manager). Instructions can be found at https://getcomposer.org/doc/00-intro.md. Quick instructions are below (but don't skip the link above!).

*nix

To download composer, run:
curl -sS https://getcomposer.org/installer | php

To be able to run composer from any directory, try:

mv composer.phar /usr/local/bin/composer

Windows

I simply downloaded and ran the installer.

Mac

I beleve installation for Mac is similar to *nix. It is covered on the link shown above.

You may see an error message: PHP Startup: Unable to load dynamic library '.../mcrypt.so'. You may need to install mcrypt, but it's also possible that you just need to add it to your path, e.g.,

export PATH=/Applications/MAMP/bin/php/php5.6.2/bin:$PATH

where the path must match the location on your machine.

All

Once composer is installed, you should:

  1. bring up a command prompt
  2. cd to a location where you want your project (I have most of mine under htdocs in the xampp folder, for example).
  3. composer create-project laravel/laravel try_laravel --prefer-dist (where try_laravel is the project name, choose a different one if you prefer).
  4. cd try_laravel
  5. php artisan serve. This brings up a web server (note that you don't need to be running Apache).
  6. open a web browser. Enter localhost:8000 for the url
  7. the laravel 5 page should appear

NOTE: if you want to be able to run laravel using Apache on *nix, there are a few more steps (you need to enable mod_rewrite and a few other details beyond the current scope.). Potentially useful information here: https://www.digitalocean.com/community/tutorials/how-to-set-up-mod_rewrite.

You may also want to review these instructions from a student using Ubuntu (thanks, Michael!). Note that these instructions were written for Laravel 4.

IDE

In a framework such as Laravel, you will typically be editing files from a number of different directories. A good IDE can make a big difference. I just started using PhpStorm. This is also the IDE used in many of the Laracasts. So far I really like it.

Configuration: Be sure to read the configuration documentation: https://confluence.jetbrains.com/display/PhpStorm/Installing+and+Configuring+XAMPP+with+PhpStorm+IDE. I downloaded a new copy of composer to make available for the IDE, but pointed to the php.exe in my xampp installation.

There's a helper that makes PhpStorm more effective with Laravel: https://github.com/barryvdh/laravel-ide-helper. The following document was also helpful (although at times confusing... I don't think I needed to do all the steps, but it was important to get the IDE helper. Be sure to get a stable version.): https://confluence.jetbrains.com/display/PhpStorm/Laravel+Development+using+PhpStorm#LaravelDevelopmentusingPhpStorm-CommandLineToolSupportforArtisanandComposer

Learning Curve: As with any IDE, there is a bit of a learning curve. I suggest you give yourself an hour or so just to do the configuration and play around and get comfortable (and of course there's lots more to learn after that... look for PhpStorm videos on Laracasts). If you find other IDEs you prefer, please post on piazza.

Getting a license: They have a student option: https://www.jetbrains.com/student/.

I also applied for licenses for this class. If you want one, send me an email and I'll send you a link.

Laravel on luna

The instructions below are to setup a laravel test project. These instructions will probably also work for your own *nix/mac machines. For Windows, you can follow the steps, but you won't need to worry about the permissions. Note that these steps will make much more sense after you've watched the Laracasts. For now, the goal is just to ensure the system is set up properly (more important on *nix than Windows, as there are more permissions to deal with).

Composer is already set up on luna (you'll need to install on your own machine, see above). You should be able to:

  1. Log onto your team directory on luna (remember it's inside the firewall)
  2. composer create-project laravel/laravel try_laravel --prefer-dist
  3. cd try_laravel
  4. chmod o+w -R storage (we must be able to write to the log files)
  5. chmod o+w -R bootstrap/cache (we must be able to update the cache files)
  6. Open a browser, navigate to (replace nn with your team number, of course):
  7. You might also try:

If you see a page that says Laravel 5, then your laravel framework was installed. The next step is to ensure you can modify files. NOTE: in the following steps, cd and/or edit paths are all relative to try_laravel.

  1. cd resources/views
  2. edit welcome.blade.php. Make some small change, e.g., add ! after Laravel 5
  3. Let's also turn on debug mode. Edit config/app.php and update the line: 'debug' => env('APP_DEBUG', true),
  4. refresh the browser

First let's update a route and ensure we can see it.

  1. cd into app/Http directory.
  2. edit routes.php
  3. Add the following:
    Route::get('/hello',function(){
        return 'Hello World!';
    	});
  4. In your browser, navigate to: [same as above]/try_laravel/public/hello

This is all good, but we need to update some more permissions on luna/*nix before we can really update the app. From the try_laravel directory, do:

  1. php artisan cache:clear
  2. composer dump-autoload

Now let's ensure we can update the app.

  1. From the try_laravel directory, type php artisan make:controller Hello
  2. cd to the app/Http/Controllers directory.
  3. edit Hello.php
  4. In the index function, type return "hello";
  5. Update routes.php. Remove or comment out the lines above, and replace with Route::get('hello', 'Hello@index');
  6. Refresh your browser to ensure this displays.

Now we need to ensure we can display a view.

  1. cd to resources/views
  2. create a new file named hello.blade.php
  3. The contents of this file can be very simple, such as:
    <!DOCTYPE html>
    <html>
        <head>
            <title>Laravel</title>
       </head>
       <body>
       HELLO FROM A VIEW
       </body>
    </html>
    
  4. Now edit app/Http/Controllers/Hello.php and change the index function to: return view('hello');
  5. Refresh the browser.

If your browser shows HELLO FROM A VIEW, then you're ready to continue with Unit 8.

Database details. For apps that involve the use of a database (e.g., Unit 8), follow the instructions below. On luna, we need to use MySQL rather than SQLite. You should be able to just modify the database.php file (in the app/config directory). Specifically, you ensure the file states: 'default' => 'mysql', and that you enter your information under connections:


		'mysql' => array(
			'driver'    => 'mysql',
			'host'      => 'localhost',
			'database'  => 'teamnn',
			'username'  => 'teamnn',
			'password'  => 'team's password',
			'charset'   => 'utf8',
			'collation' => 'utf8_unicode_ci',
			'prefix'    => '',
		),

As in other settings, you will need to setup the database table before running your app. For luna, you should log onto a terminal window (e.g., using putty or ssh) and then run php artisan migrate and php artisan db:seed.

NOTE: We have limited space on laravel. As you move on to doing the homework assignments, you should remove the test project, so that we don't run out of space.

Laravel errors

Along the way I've made a few typos and/or mistakes. (OK, quite a few) The table below lists some errors I've encountered. Can you add to the list? (good for class participation points)

syntax error, unexpected '}', expecting ',' or ';'

Sounds like I have an extra }, but this was caused by leaving off one } in:
{{URL::to('books/'.$book->id.'')}"> ← Cancel

unexpected end of file

Forgot to close a construct, such as @endif to match @unless

syntax error, unexpected ':', expecting ',' or ';'

In a form, typed Form:label rather than Form::label

syntax error, unexpected 'delete' (T_STRING)

Didn't close quotations around post: @if($method == 'post) should have been 'post'

Undefined variable: id

Error message displayed and the following route was highlighted:
Route::get('books/{id}', function() {

Solution: need to pass the id into the function, so it can be used in the find, etc.
Route::get('books/{id}', function($id) {

[ReflectionException] Class BooksTableSeeder does not exist

Forgot to put <?php at the top of the file

{"error":{"type": "Symfony\\Component\\Debug\\Exception\\FatalErrorException","message": "syntax error, unexpected '}'","file":"C:\\BirdSeederTable.php,"line":12}}

Message displayed when running php artisan db:seed. Issue: missing ); at end of insert array:

	
	DB::table('books')->insert(array(
		array('id'=>1, 'title'=>'Animal Minds', 'author'=>'Griffin'),
	)

should be:

	
	DB::table('books')->insert(array(
		array('id'=>1, 'title'=>'Animal Minds', 'author'=>'Griffin'),
	));

Argument 1 passed to {closure}() must be an instance of Book, string given

Error occurs when trying to edit an existing entry (book). Highlights route:
Route::get('books/{book}/edit', function(Book $book) {

Solution: need to bind a parameter to a model (http://laravel.com/docs/4.2/routing#route-model-binding).

At the top of your routes file, add a line such as:Route::model('book', 'Book');

created_at may not be null

When seeding, the timestamp is not created automatically. For now, I would recommend setting timestamps to false.

Cannot redeclare class [name of migration file]

Error occurs when trying to run php artisan migrate. Redeclare is the key here... see if you have two migrations both creating the same database table(s).

Integrity constraint violation: PRIMARY KEY must be unique [class name]

Check the seed file, probably due to cut-and-paste you haven't used unique ids.

It's probably a good idea to delete records before seeding, e.g., DB::table('quotes')->delete();

Database does not exist

Make sure you have a production.sqlite file in app/database. You can also run sqlite3 in that directory and then the command .tables (it's ugly, but at least you can see what's in your database).

Database column not updated

Name in form does not match database column. E.g., {{Form::text('athor')}} when the field name is author. No error message is displayed, but the data you type into the field is not saved.

Relationship not working

Be sure the name of your foreign key is not the same as the table name. I had a table named genre and a foreign key named genre. Didn't work. Foreign key needed to be genre_id.

Other material

A few other links I found helpful as I was working on the authentication tutorials:

Why Laravel? A few thoughts from the trenches