Readouble

Laravel 4.2 Laravelクイックスタート

インストールInstallation

LaravelインストーラーVia Laravel Installer

最初にComposerを使用し、Laravelインストーラーをダウンロードします。First, download the Laravel installer using Composer.

composer global require "laravel/installer=~1.1"

端末で、laravelコマンドが実行できるように、~/.composer/vendor/bin(Windowsの場合は、C:\%HOMEPATH%\AppData\Roaming\Composer\vendor\bin)ディレクトリーへPATHを通してください。Make sure to place the ~/.composer/vendor/bin directory in your PATH (or C:\%HOMEPATH%\AppData\Roaming\Composer\vendor\bin if working with Windows) so the laravel executable is found when you run the laravel command in your terminal.

インストールが完了したら、後はただlaravel newコマンドで、指定したディレクトリーに真新しいLaravelプロジェクトが作成されます。例えば、laravel new blogと打ち込めば、blogというディレクトリーに、必要なパッケージが全部揃って、Laravelがインストールされます。このインストール方法は、Composerを使うよりも多少早いです。Once installed, the simple laravel new command will create a fresh Laravel installation in the directory you specify. For instance, laravel new blog would create a directory named blog containing a fresh Laravel installation with all dependencies installed. This method of installation is much faster than installing via Composer.

コンポーサーによるインストールVia Composer

LaravelフレームワークはComposerをインストールと依存パッケージの管理に活用しています。まだ用意していない場合は、installing Composerの手順でインストールしてください。The Laravel framework utilizes Composer[http://getcomposer.org] for installation and dependency management. If you haven't already, start by installing Composer[http://getcomposer.org/doc/00-intro.md].

では、端末から次のコマンドを実行し、Laravelをインストールしましょう。Now you can install Laravel by issuing the following command from your terminal:

composer create-project laravel/laravel your-project-name --prefer-dist

このコマンドでLaravelの最新パッケージがダウンロードされ、現在のディレクトリーの中の、新しいyour-project-nameフォルダーにインストールされます。This command will download and install a fresh copy of Laravel in a new your-project-name folder within your current directory.

別の方法がお好みであれば、GitHubのLaravelリポジトリーから手動でダウンロードできます。次に、手動で作成したディレクトリーのルートで、composer installコマンドを実行してください。このコマンドによりフレームワークに必要な依存パッケージがインストールされます。If you prefer, you can alternatively download a copy of the Laravel repository from GitHub[https://github.com/laravel/laravel/archive/master.zip] manually. Next run the composer install command in the root of your manually created project directory. This command will download and install the framework's dependencies.

パーミッションPermissions

Laravelをインストールしたら、app/storage下のディレクトリーへサーバーが書き込めるように許可を与える必要があります。詳細については、インストールを確認してください。After installing Laravel, you may need to grant the web server write permissions to the app/storage directories. See the Installation[/docs/4.2/installation] documentation for more details on configuration.

LaravelのサーバーServing Laravel

Laravelのアプリケーションは通常ApacheやNginxなどのWebサーバーを使用して、通常動作させます。もしも、PHP5.4以上を使用しているのであれば、Artisan 'serve'コマンドで、PHPの組み込み開発サーバーを使用できます。Typically, you may use a web server such as Apache or Nginx to serve your Laravel applications. If you are on PHP 5.4 and would like to use PHP's built-in development server, you may use the serve Artisan command:

php artisan serve

HTTPサーバーはデフォルトで8000ポートをリッスンします。しかし、既に使用済みであるか、この方法で複数のサーバーを建てたい場合は、対象のポート番号を指定します。--port引数を使うだけです。By default the HTTP-server will listen to port 8000. However if that port is already in use or you wish to serve multiple applications this way, you might want to specify what port to use. Just add the --port argument:

php artisan serve --port=8080

ディレクトリー構造Directory Structure

フレームワークをインストールしたら、プロジェクトをチェックして、ディレクトリー構造に馴染んでください。appディレクトリーはviewscontrollersmodelsのようなフォルダーで構成されています。ほとんどのアプリケーションのコードはこのディレクトリーの中に設置します。またapp/configディレクトリーも調査してみてください。設定可能なオプションが用意されています。After installing the framework, take a glance around the project to familiarize yourself with the directory structure. The app directory contains folders such as views, controllers, and models. Most of your application's code will reside somewhere in this directory. You may also wish to explore the app/config directory and the configuration options that are available to you.

ローカル開発環境Local Development Environment

今まで、自分のローカルマシーンで、PHP開発環境を整えるのは頭痛の種でした。正しいPHPバージョンと必要な拡張、それに他の必要なコンポーネントをインストールするのは、時間がかかり、混乱を産みました。代わりに、Laravel Homesteadを利用してください。Homesteadはシンプルなバーチャルマシーンで、LaravelとVagrantのために設計されています。Homesteadは、堅牢なPHPアプリケーションを構築するために必要な、全てのソフトウエアーを予めパッケージしたVagrat boxですから、あっという間に仮想化された、独立した環境が作成できます。Homesteadに含まれているソフトウェアのリストをご覧ください。In the past, configuring a local PHP development environment on your machine was a headache. Installing the proper version of PHP, required extensions, and other needed components is time consuming and confusing. Instead, consider using Laravel Homestead[/docs/4.2/homestead]. Homestead is a simple virtual machine designed for Laravel and Vagrant[http://vagrantup.com]. Since the Homestead Vagrant box is pre-packaged with all of the software you need to build robust PHP applications, you can create a virtualized, isolated development environment in seconds. Here is a list of some of the goodies included with Homestead:

  • NginxNginx
  • PHP 5.6PHP 5.6
  • MySQLMySQL
  • RedisRedis
  • MemcachedMemcached
  • BeanstalkBeanstalk

「仮想化」という言葉が難しそうに聞こえても、何も心配ありません。苦労なしです。Homesteadに必要な、VirtualBoxとVagrantの2つには、人気のある全オペレーティングシステム用に、簡単でグラフィカルなインストーラーが用意されています。使用開始するには、Homesteadのドキュメントを確認してください。Don't worry, even though "virtualized" sounds complicated, it's painless. VirtualBox and Vagrant, which are Homestead's two dependencies, both include simple, graphical installers for all popular operating systems. Check out the Homestead documentation[/docs/4.2/homestead] to get started.

ルーティングRouting

スタートを切るために、最初のルートを作成しましょう。Laravelの一番シンプルなルートはクロージャーです。app/routes.phpファイルを開き、ファイルの最後に以下のルートを付け加えてください。To get started, let's create our first route. In Laravel, the simplest route is a route to a Closure. Pop open the app/routes.php file and add the following route to the bottom of the file:

Route::get('users', function()
{
	return 'Users!';
});

Webブラウザーで/usersへアクセスすれば、レスポンスとしてUsers!と表示されます。素晴らしい!これで最初のルートが出来上がりました。Now, if you hit the /users route in your web browser, you should see Users! displayed as the response. Great! You've just created your first route.

ルートはコントローラークラスで指定することもできます。例えば:Routes can also be attached to controller classes. For example:

Route::get('users', 'UserController@getIndex');

このルートがフレームワークに伝えているのは、/usersへのアクセスでUserControllerクラスのgetIndexメソッドが呼び出されるという内容です。コントローラールーティングの詳細は、コントローラーのドキュメントをご覧下さい。This route informs the framework that requests to the /users route should call the getIndex method on the UserController class. For more information on controller routing, check out the controller documentation[/docs/4.2/controllers].

ビューの作成Creating A View

次に、ユーザーデータを表示するシンプルなビューを作成しましょう。ビューはapp/viewsディレクトリーに設置し、アプリケーションのHTMLで構成されています。2つの新しいビューをこのディレクトリーに作成します。layout.blade.phpusers.blade.phpです。まず最初にlayout.blade.phpを作成しましょう。Next, we'll create a simple view to display our user data. Views live in the app/views directory and contain the HTML of your application. We're going to place two new views in this directory: layout.blade.php and users.blade.php. First, let's create our layout.blade.php file:

<html>
	<body>
		<h1>Laravelクイックスタート</h1>

		@yield('content')
	</body>
</html>

次に、users.blade.phpビューを作成します。Next, we'll create our users.blade.php view:

@extends('layout')

@section('content')
	Users!
@stop

この構文は多分とても奇妙に思えることでしょう。その理由はLaravelのテンプレートエンジンであるBladeを使用しているからです。BladeはテンプレートをPHPへコンパイルするのに正規表現を使用しているだけですのでとても早いのです。Bladeはテンプレートの継承などパワフルな機能性と同時に、ifforのようなPHPの典型的な制御構文の使いやすい代用構文を提供しています。詳細はBladeのドキュメントをご覧ください。Some of this syntax probably looks quite strange to you. That's because we're using Laravel's templating system: Blade. Blade is very fast, because it is simply a handful of regular expressions that are run against your templates to compile them to pure PHP. Blade provides powerful functionality like template inheritance, as well as some syntax sugar on typical PHP control structures such as if and for. Check out the Blade documentation[/docs/4.2/templates] for more details.

ビューを見てみました。ここで/usersルートへ戻ります。Users!文字列をリターンする代わりに、ビューを戻します。Now that we have our views, let's return it from our /users route. Instead of returning Users! from the route, return the view instead:

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

素晴らしい!!これでレイアウトを拡張するシンプルなビューの準備ができました。次にデータベースレイヤーにとりかかりましょう。Wonderful! Now you have setup a simple view that extends a layout. Next, let's start working on our database layer.

マイグレーションの作成Creating A Migration

データを保存するためのテーブルを作成するには、Laravelのマイグレーションシステムを使用します。マイグレーションはデータベースの修正内容を記述的に適宜し、あなたのチームメンバーと簡単に共有できるようにしてくれます。To create a table to hold our data, we'll use the Laravel migration system. Migrations let you expressively define modifications to your database, and easily share them with the rest of your team.

最初にデータベース接続の設定を行いましょう。app/config/database.phpファイルでデータベース接続に関する全設定を行います。LaravelはデフォルトとしてMySQLを設定しており、データベース設定ファイル中で接続情報を指定する必要があります。ご希望であれば、driversqliteに変更すれば、app/databaseの中のSQLiteデータベースが取り込まれ、使用できるようになります。First, let's configure a database connection. You may configure all of your database connections from the app/config/database.php file. By default, Laravel is configured to use MySQL, and you will need to supply connection credentials within the database configuration file. If you wish, you may change the driver option to sqlite and it will use the SQLite database included in the app/database directory.

次にマイグレーションを作成しましょう。Artsanコマンドラインツールが使用できます。ターミナルを起動し、プロジェクトのルートディレクトリーで以下のコマンドを入力してください。Next, to create the migration, we'll use the Artisan CLI[/docs/4.2/artisan]. From the root of your project, run the following from your terminal:

php artisan migrate:make create_users_table

次にapp/database/migrationsフォルダーの中に生成されたマイグレーションを見つけてください。このファイルには一つのクラスと2つのメソッド、updownを含んでいます。upメソッドにはデータベーステーブルに対する変更を記述し、downメソッドにはその変更をもとに戻す指定を記述します。Next, find the generated migration file in the app/database/migrations folder. This file contains a class with two methods: up and down. In the up method, you should make the desired changes to your database tables, and in the down method you simply reverse them.

マイグレーションを定義してみましょう。以下のようになります。Let's define a migration that looks like this:

public function up()
{
	Schema::create('users', function($table)
	{
		$table->increments('id');
		$table->string('email')->unique();
		$table->string('name');
		$table->timestamps();
	});
}

public function down()
{
	Schema::drop('users');
}

次にターミナルでmigrateコマンドを使い、マイグレーションを実行します。プロジェクトのルートディレクトリーでこのコマンドを実行してください。Next, we can run our migrations from our terminal using the migrate command. Simply execute this command from the root of your project:

php artisan migrate

マイグレーションをロールバックしたければ、migrate:rollbackコマンドを発行します。これでデータベーステーブルができました。続いてデータを取り出しましょう!If you wish to rollback a migration, you may issue the migrate:rollback command. Now that we have a database table, let's start pulling some data!

Eloquent ORMEloquent ORM

Laravelは素晴らしいORMであるEloquentを持っています。もしRuby on Railsフレームワークを使用したことがあれば、Eloquentが似ていることに気がつくでしょう。ActiveRecord ORMスタイルでデータベースとやり取りする手法を提供しているからです。Laravel ships with a superb ORM: Eloquent. If you have used the Ruby on Rails framework, you will find Eloquent familiar, as it follows the ActiveRecord ORM style of database interaction.

最初にモデルを定義します。Eloquentモデルでは、指定したテーブルの行を代表として、関連するデーターベーステーブルにクエリーすることが可能です。心配しないでください。すぐに納得できますよ!典型的な使用では、モデルをapp/modelsに設置します。このディレクトリーにUser.phpモデルを定義してみましょう。First, let's define a model. An Eloquent model can be used to query an associated database table, as well as represent a given row within that table. Don't worry, it will all make sense soon! Models are typically stored in the app/models directory. Let's define a User.php model in that directory like so:

class User extends Eloquent {}

Eloquentにどのテーブルを使用するか指定していないことに注目してください。Eloquentには様々な規約があり、そのうちの一つは「データベース名は、モデル名の複数形を使用する」というものです。便利でしょう!Note that we do not have to tell Eloquent which table to use. Eloquent has a variety of conventions, one of which is to use the plural form of the model name as the model's database table. Convenient!

お好みのデータベース管理ツールを使い、usersテーブルに数行のデータをインサートしてください。Eloquentで取得し、ビューに渡してみましょう。Using your preferred database administration tool, insert a few rows into your users table, and we'll use Eloquent to retrieve them and pass them to our view.

では、/usersルートを以下のように変更して下さい。Now let's modify our /users route to look like this:

Route::get('users', function()
{
	$users = User::all();

	return View::make('users')->with('users', $users);
});

このルートを一緒に確認してみましょう。最初にallメソッドをUserモデルに使用し、usersテーブルから全レコードを取得します。次に、取得したレコードをwithメソッドを使用しビューに渡します。withメソッドにはキーと値を渡し、それはビューで使用できる変数となります。Let's walk through this route. First, the all method on the User model will retrieve all of the rows in the users table. Next, we're passing these records to the view via the with method. The with method accepts a key and a value, and is used to make a piece of data available to a view.

素晴らしい。ではビューにユーザーを表示しましょう!Awesome. Now we're ready to display the users in our view!

データの表示Displaying Data

ではusersをビューで使用できるようにしてみましょう。以下のように行います。Now that we have made the users available to our view, we can display them like so:

@extends('layout')

@section('content')
	@foreach($users as $user)
		<p>{{ $user->name }}</p>
	@endforeach
@stop

echo文はどこかと不思議に思えるでしょう。Bladeを使えば、二重の中括弧で囲んだデーターをechoできます。朝飯前です。ここで、/usersルートにアクセスすれば、レスポンスとしてユーザー達の名前が表示されます。You may be wondering where to find our echo statements. When using Blade, you may echo data by surrounding it with double curly braces. It's a cinch. Now, you should be able to hit the /users route and see the names of your users displayed in the response.

これは始まりにすぎません。このチュートリアルではLaravelの基本をご覧いただきました。しかし習得していただくもっとエキサイティングな項目が用意されています。ドキュメントを読み進めていただき、EloquentBladeのパワフルな機能を深く追求してください。またはキューユニットテストのほうがもっと興味深いかも知れません。それともIoCコンテナを使用した柔軟なアーキテクチャをお望みでしょうか。お好きなものをお選びください!This is just the beginning. In this tutorial, you've seen the very basics of Laravel, but there are so many more exciting things to learn. Keep reading through the documentation and dig deeper into the powerful features available to you in Eloquent[/docs/4.2/eloquent] and Blade[/docs/4.2/templates]. Or, maybe you're more interested in Queues[/docs/4.2/queues] and Unit Testing[/docs/4.2/testing]. Then again, maybe you want to flex your architecture muscles with the IoC Container[/docs/4.2/ioc]. The choice is yours!

アプリケーションのデプロイDeploying Your Application

Laravelが持っている目標の一つは、PHPアプリケーション開発をダウンロードからデプロイまで、楽しめるものにすることです。Laravel Forgeは、素晴らしく早いサーバーへLaravelアプリケーションをデプロイする、簡単な方法を提供します。Forgeは、DigitalOcean、Linode、Rackspace、Amazon EC2のサーバー設定と事前準備(プロビジョン)が行えます。Homesteadと同様、Nginx、PHP5.6、MySQL、Postgres、Redis、Memcached、その他の最新ソフトウェアが全部含まれています。Forgeの"Quick Deploy"は、GithubかBitbucketに変更のコードをPushするたび、デプロイしてくれます!One of Laravel's goals is to make PHP application development enjoyable from download to deploy, and Laravel Forge[https://forge.laravel.com] provides a simple way to deploy your Laravel applications onto blazing fast servers. Forge can configure and provision servers on DigitalOcean, Linode, Rackspace, and Amazon EC2. Like Homestead, all of the latest goodies are included: Nginx, PHP 5.6, MySQL, Postgres, Redis, Memcached, and more. Forge "Quick Deploy" can even deploy your code for you each time you push changes out to GitHub or Bitbucket!

それに付け加え、Forgeはキューワーカー、SSL、Cronジョブ、サブドメイン、その他の設定も手助けします。詳しい情報は、Forge websiteでご覧ください。On top of that, Forge can help you configure queue workers, SSL, Cron jobs, sub-domains, and more. For more information, visit the Forge website[https://forge.laravel.com].

章選択

Artisan CLI

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

Pagination和文
ペジネーション
ペギネーション
ページネーション
ページ付け
Scaffold和文
スカフォールド
スキャフォールド
型枠生成
本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作