Laravel5.1ハンズオンを追ってみる1


”[composer使う時にgithubのトークンを聞かれた](http://qiita.com/n0bisuke/items/54169b5e3800f792b8df)”の続きです。

メモ書きに近いかも。

## artisanコマンドを確認します。

`laravel5-handson`フォルダ内で以下を実行しましょう。

```bash
$ php artisan
Laravel Framework version 5.1.19 (LTS)

Usage:
  command [options] [arguments]

Options:
  -h, --help            Display this help message
  -q, --quiet           Do not output any message
  -V, --version         Display this application version
      --ansi            Force ANSI output
      --no-ansi         Disable ANSI output
  -n, --no-interaction  Do not ask any interactive question
      --env[=ENV]       The environment the command should run under.
  -v|vv|vvv, --verbose  Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

Available commands:
  _
  clear-compiled      Remove the compiled class file
  down                Put the application into maintenance mode
  env                 Display the current framework environment
  help                Displays help for a command
  inspire             Display an inspiring quote
  list                Lists commands
  optimize            Optimize the framework for better performance
  serve               Serve the application on the PHP development server
  tail                [+] Tail a log file
  tinker              Interact with your application
  up                  Bring the application out of maintenance mode
 addon
  addon:check         [+] Check addons
  addon:name          [+] Set the addon PHP namespace
  addon:remove        [+] Remove addon.
  addon:status        [+] List up addon information
 app
  app:container       [+] Lists object in application container
  app:name            Set the application namespace
 auth
  auth:clear-resets   Flush expired password reset tokens
 cache
  cache:clear         Flush the application cache
  cache:table         Create a migration for the cache database table
 config
  config:cache        Create a cache file for faster configuration loading
  config:clear        Remove the configuration cache file
 database
  database:again      [+] Migrations rollback latest version and upgrade
  database:clean      [+] Database migrate to clean
  database:refresh    [+] Database migrate to clean, and migrate to latest version
  database:rollback   [+] Database migrate to back to one or specifed version
  database:seed       [+] Insert seed to database
  database:status     [+] Display migration status
  database:upgrade    [+] Database migration to latest version
 debugbar
  debugbar:clear      Clear the Debugbar Storage
 event
  event:generate      Generate the missing events and listeners based on registration
 hash
  hash:check          [+] Check hashed value
  hash:make           [+] Make hashed value
 key
  key:generate        Set the application key
 make
  make:addon          [+] Make addon
  make:console        [+] Create a new Artisan command
  make:controller     [+] Create a new resource controller class
  make:event          [+] Create a new event class
  make:job            [+] Create a new job class
  make:listener       [+] Create a new event listener class
  make:middleware     [+] Create a new middleware class
  make:migration      [+] Create a new migration class
  make:model          [+] Create a new Eloquent model class
  make:policy         [+] Create a new policy class
  make:provider       [+] Create a new service provider class
  make:request        [+] Create a new form request class
  make:seeder         [+] Create a new seeder class
  make:test           [+] Create a new test class
 queue
  queue:failed        List all of the failed queue jobs
  queue:failed-table  Create a migration for the failed queue jobs database table
  queue:flush         Flush all of the failed queue jobs
  queue:forget        Delete a failed queue job
  queue:listen        Listen to a given queue
  queue:restart       Restart queue worker daemons after their current job
  queue:retry         Retry a failed queue job
  queue:subscribe     Subscribe a URL to an Iron.io push queue
  queue:table         Create a migration for the queue jobs database table
  queue:work          Process the next job on a queue
 route
  route:cache         Create a route cache file for faster route registration
  route:clear         Remove the route cache file
  route:list          List all registered routes
 schedule
  schedule:run        Run the scheduled commands
 session
  session:table       Create a migration for the session database table
 vendor
  vendor:publish      Publish any publishable assets from vendor packages
 view
  view:clear          Clear all compiled view files
```

こんな感じでリストが表示されればOKです。

### 環境変数の確認

```bash
$ php artisan env
Current application environment: local
```

localという表示が確認できると思います。

Atomで開いてみます。

```bash
$ atom .
```

プロジェクトファイル内に`.env`というフォルダがあり、ここのAPP_ENVの値が確認できると思います。
![](https://i.gyazo.com/05ca4f4034ba26bef0d095c023f6848c.png)

## サーバーを起動してみる

```bash
$ php artisan serv
Laravel development server started on http://localhost:8000/
[Sat Oct 10 14:52:33 2015] ::1:54350 [200]: /favicon.ico
```

ブラウザから http://localhost:8000 にアクセスしましょう。

![](https://i.gyazo.com/a55af22ab0861bc47cdc7ac0ffc3f0f6.png)

こんな表示がされればOKです。

## ログの確認

`storage/logs/laravel.log`にログがたまるらしいです。

※MAMP使ってることがバレるログだ..w

```
$ tail storage/logs/laravel.log

#3 /Applications/MAMP/htdocs/laravel5-handson/vendor/laravel/framework/src/Illuminate/Container/Container.php(503): call_user_func_array(Array, Array)
#4 /Applications/MAMP/htdocs/laravel5-handson/vendor/laravel/framework/src/Illuminate/Console/Command.php(150): Illuminate\Container\Container->call(Array)
#5 /Applications/MAMP/htdocs/laravel5-handson/vendor/symfony/console/Command/Command.php(259): Illuminate\Console\Command->execute(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#6 /Applications/MAMP/htdocs/laravel5-handson/vendor/laravel/framework/src/Illuminate/Console/Command.php(136): Symfony\Component\Console\Command\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#7 /Applications/MAMP/htdocs/laravel5-handson/vendor/symfony/console/Application.php(878): Illuminate\Console\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#8 /Applications/MAMP/htdocs/laravel5-handson/vendor/symfony/console/Application.php(195): Symfony\Component\Console\Application->doRunCommand(Object(LaravelPlus\Extension\Console\TailCommand), Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#9 /Applications/MAMP/htdocs/laravel5-handson/vendor/symfony/console/Application.php(126): Symfony\Component\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#10 /Applications/MAMP/htdocs/laravel5-handson/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(100): Symfony\Component\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#11 /Applications/MAMP/htdocs/laravel5-handson/artisan(36): Illuminate\Foundation\Console\Kernel->handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#12 {main}
```

## ルーティング設定してみる

app/Http/routes.phpを編集します。

http://localhost:8000/textにアクセスしたときの処理を書いてみましょう。

`Route::get('text', function () {})`を追記していきます。

```routes.php
<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

Route::get('/', function () {
	Log::debug('URL "/" にアクセスされました。');

    return view('welcome');
});

/**
追記
**/
Route::get('text', function () {
	Log::debug('URL "text" にアクセスされました。');
  return 'こんにちは!';
});
```

http://localhost:8000/text にアクセスしてみます。 `こんにちは！`と表示されればOKです。

![](https://i.gyazo.com/c94382762a6f7ddfb9896989d4b98786.png)

`php artisan route:list`でも確認できます。

```bash
$ php artisan route:list

php artisan route:list
+--------+----------+------------------------------+----------------------+---------------------------------------------------------------+------------+
| Domain | Method   | URI                          | Name                 | Action                                                        | Middleware |
+--------+----------+------------------------------+----------------------+---------------------------------------------------------------+------------+
|        | GET|HEAD | /                            |                      | Closure                                                       |            |
|        | GET|HEAD | _debugbar/assets/javascript  | debugbar.assets.js   | Barryvdh\Debugbar\Controllers\AssetController@js              |            |
|        | GET|HEAD | _debugbar/assets/stylesheets | debugbar.assets.css  | Barryvdh\Debugbar\Controllers\AssetController@css             |            |
|        | GET|HEAD | _debugbar/clockwork/{id}     | debugbar.clockwork   | Barryvdh\Debugbar\Controllers\OpenHandlerController@clockwork |            |
|        | GET|HEAD | _debugbar/open               | debugbar.openhandler | Barryvdh\Debugbar\Controllers\OpenHandlerController@handle    |            |
|        | GET|HEAD | debug/info                   |                      | Closure                                                       |            |
|        | GET|HEAD | text                         |                      | Closure                                                       |            |
+--------+----------+------------------------------+----------------------+---------------------------------------------------------------+------------+
```

### 配列表示をしてみましょう。

routes.phpに以下を追記して

```routes.php
Route::get('array', function () {
	Log::debug('URL "text" にアクセスされました。');
  return ['now' => 'Laravel5.1体験中！', 'date' => new DateTime];
});
```

http://localhost:8000/array にアクセスしましょう。

![](https://i.gyazo.com/fa5825b405254eb3b4717153d1e4d006.png)

こんな感じで **jsonにして表示してくれます。** returnに配列指定するだけでjsonにしてくれる機能、これは便利ですね。

```
{
 now: "Laravel5.1体験中！",
 date: {
  date: "2015-10-10 15:12:07.000000",
  timezone_type: 3,
  timezone: "Asia/Tokyo"
 }
}
```


## Appコントローラークラスを生成する
以下のコマンドを実行しましょう。

```bash
$ php artisan make:controller AppController --plain
Controller created successfully.
```

`app/Http/Controllers/AppController.php`が生成されます。

```AppController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class AppController extends Controller
{
    //
}

```

`AppController.php`にメソッドを追記しましょう。

```AppController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class AppController extends Controller
{
    /**
    追記メソッド
    **/
    public function status(){
      return 'コーディングなう。';
    }
}

```

これでstatusメソッドが作成されました。

`routes.php`に追記して先ほどのコントローラーメソッドを指定します。

```routes.php
Route::get('status', 'AppController@status');
```

これで /statusにアクセスがきたらAppController内のstatusメソッドが呼ばれます。

ブラウザから http://localhost:8000/status にアクセスしましょう。
![](https://i.gyazo.com/4a2b2be87fa91e3579558a34427b2488.png)


## viewを扱う

![](https://i.gyazo.com/23d6e6784588fb818521b3046816c305.png)


```
    public function getApp() {
      return view('app');
    }
```

書きかけなので後で追記します。