m_shige1979のときどきITブログ

プログラムの勉強をしながら学習したことや経験したことをぼそぼそと書いていきます

Github(変なおっさんの顔でるので気をつけてね)

https://github.com/mshige1979

Laravel4のチュートリアル2

最初からやり直し

これ見たけどなんかlaravelで簡単にできそうだけどどんな中身かわからなかったので…

手順

composerをインストール
mkdir laravel1
cd laravel1
curl -sS https://getcomposer.org/installer | php
php composer.phar create-project laravel/laravel app1 

※結構インストールするものがあるから時間がかかる

データベースを作成
mysql -uroot -e "create database laravel_db;";

設定

app/config/app.php
	'timezone' => 'Asia/tokyo',

※timezoneをUTC→Asia/Tokyoへ

app/config/database.php
		'mysql' => array(
			'driver'    => 'mysql',
			'host'      => 'localhost',
			'database'  => 'laravel_db',
			'username'  => 'root',
			'password'  => '',
			'charset'   => 'utf8',
			'collation' => 'utf8_unicode_ci',
			'prefix'    => '',
		),

※デフォルトでmysqlなのでその部分を変更

バージョンを確認
[vagrant@localhost app1]$ php artisan --version
Laravel Framework version 4.2.6
[vagrant@localhost app1]$
確認
[vagrant@localhost app1]$ php artisan serve --host=192.168.33.10
Laravel development server started on http://192.168.33.10:8000

f:id:m_shige1979:20140718060129p:plain

ジェネレータ導入

composer.jsonに追加
    "require-dev": {
        "way/generators": "2.*"
    }
update
php ../composer.phar update
app/config/app.php
        'Way\Generators\GeneratorsServiceProvider',

※providersに追加

コマンド確認
generate
  generate:controller          Generate a controller
  generate:migration           Generate a new migration
  generate:model               Generate a model
  generate:pivot               Generate a pivot table
  generate:publish-templates   Copy generator templates for user modification
  generate:resource            Generate a new resource
  generate:scaffold            Scaffold a new resource (with boilerplate)
  generate:seed                Generate a database table seeder
  generate:view                Generate a view
key
  key:generate                 Set the application key
migrate
  migrate:install              Create the migration repository
  migrate:make                 Create a new migration file
  migrate:publish              Publish a package's migrations to the application
  migrate:refresh              Reset and re-run all migrations
  migrate:reset                Rollback all database migrations
  migrate:rollback             Rollback the last database migration
雛形作成
[vagrant@localhost app1]$ php artisan generate:scaffold post --fields="title:string, body:text"
Do you want me to create a Post model? [yes|no] 
Created: /vagrant/laravel1/app1/app/models/Post.php
Do you want me to create views for this Post resource? [yes|no] 
Created: /vagrant/laravel1/app1/app/views/posts/index.blade.php
Created: /vagrant/laravel1/app1/app/views/posts/show.blade.php
Created: /vagrant/laravel1/app1/app/views/posts/create.blade.php
Created: /vagrant/laravel1/app1/app/views/posts/edit.blade.php
Do you want me to create a PostsController controller? [yes|no] 
Created: /vagrant/laravel1/app1/app/controllers/PostsController.php
Do you want me to create a 'create_posts_table' migration and schema for this resource? [yes|no] 
Created: /vagrant/laravel1/app1/app/database/migrations/2014_07_18_072514_create_posts_table.php
Generating optimized class loader
Compiling common classes
Compiling views
Would you like a 'Posts' table seeder? [yes|no] 
Created: /vagrant/laravel1/app1/app/database/seeds/PostsTableSeeder.php
Do you want to go ahead and migrate the database? [yes|no] 
**************************************
*     Application In Production!     *
**************************************

Do you really wish to run this command? 
Migrated: 2014_07_18_072514_create_posts_table
Done!
All done! Don't forget to add 'Route::resource('posts', 'PostsController');` to app/routes.php.

[vagrant@localhost app1]$
app/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 Closure to execute when that URI is requested.
|
*/

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

Route::resource('posts', 'PostsController');
app/controllers/PostsController.php
<?php

class PostsController extends \BaseController {

	/**
	 * Display a listing of posts
	 *
	 * @return Response
	 */
	public function index()
	{
		$posts = Post::all();

		return View::make('posts.index', compact('posts'));
	}

	/**
	 * Show the form for creating a new post
	 *
	 * @return Response
	 */
	public function create()
	{
		return View::make('posts.create');
	}

	/**
	 * Store a newly created post in storage.
	 *
	 * @return Response
	 */
	public function store()
	{
		$validator = Validator::make($data = Input::all(), Post::$rules);

		if ($validator->fails())
		{
			return Redirect::back()->withErrors($validator)->withInput();
		}

		Post::create($data);

		return Redirect::route('posts.index');
	}

	/**
	 * Display the specified post.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function show($id)
	{
		$post = Post::findOrFail($id);

		return View::make('posts.show', compact('post'));
	}

	/**
	 * Show the form for editing the specified post.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{
		$post = Post::find($id);

		return View::make('posts.edit', compact('post'));
	}

	/**
	 * Update the specified post in storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id)
	{
		$post = Post::findOrFail($id);

		$validator = Validator::make($data = Input::all(), Post::$rules);

		if ($validator->fails())
		{
			return Redirect::back()->withErrors($validator)->withInput();
		}

		$post->update($data);

		return Redirect::route('posts.index');
	}

	/**
	 * Remove the specified post from storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
	{
		Post::destroy($id);

		return Redirect::route('posts.index');
	}

}

※これはそのまま

app/models/Post.php
<?php

class Post extends \Eloquent {

	// Add your validation rules here
	public static $rules = [
		// 'title' => 'required'
	];

	// Don't forget to fill this array
	protected $fillable = [];

}

※これはそのまま

app/views/posts/index.blade.php
/vagrant/laravel1/app1/app/views/posts/index.blade.php

※は???

↓へ修正

<!DOCType html>
<html>
    <head>
        <title>post test</title>
    </head>
    <body>
        <h1>post test</h1>

        <table border="1">
        @foreach ($posts as $post)
            <tr>
                <td>{{{ $post->id }}}</td>
                <td>{{{ $post->title }}}</td>
                <td>{{{ $post->body }}}</td>
                <td>{{{ $post->created_at }}}</td>
            </tr>
        @endforeach
        </table>

    </body>
</html>

↓確認

f:id:m_shige1979:20140718073942p:plain

まとめてないけどまとめ

マイグレーションが便利かどうかはともかく取りあえず動く感じにはできる。
フレームワークなどを見ると全体の構成に惑わされて難しそうに意識して時間がかかっている感じがするので
もう少しシンプルに考えてみることが必要と思う。

いろいろな機能をどうするかではなくとりあえず動くものを作ってから調整していこう。