Documentation Laravel 4 / Документация по Laravel 4

→# Laravel Quickstart

- [Installation](#installation)
- [Routing](#routing)
- [Creating A View](#creating-a-view)
- [Creating A Migration](#creating-a-migration)
- [Eloquent ORM](#eloquent-orm)
- [Displaying Data](#displaying-data)

<a name="installation"></a>
## Installation

To install the Laravel framework, download a copy of the [repository from Github](https://github.com/laravel/laravel/archive/master.zip). Next, after [installing Composer](http://getcomposer.org), run the `composer install` command in the root of your project directory. This command will download and install the framework's dependencies.

You may also install Laravel by issuing the following command from your terminal:

composer create-project laravel/laravel

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.

<a name="routing"></a>
## Routing

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!';
});

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');

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/controllers).

<a name="creating-a-view"></a>
## Creating A View

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 Quickstart</h1>

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

Next, we'll create our `users.blade.php` view:

@extends('layout')

@section('content')
Users!
@stop

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/templates) for more details.

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.

<a name="creating-a-migration"></a>
## Creating A Migration

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.

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 SQLite, and an SQLite database is included in the `app/database` directory. If you wish, you may change the `driver` option to `mysql` and configure the `mysql` connection credentials within the database configuration file.

Next, to create the migration, we'll use the [Artisan CLI](/docs/artisan). From the root of your project, run the following from your terminal:

php artisan migrate:make create_users_table

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');
}

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

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!

<a name="eloquent-orm"></a>
## Eloquent 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.

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 {}

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!

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.

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);
});

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!

<a name="displaying-data"></a>
## Displaying Data

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

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.

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/eloquent) and [Blade](/docs/templates). Or, maybe you're more interested in [Queues](/docs/queues) and [Unit Testing](/docs/testing). Then again, maybe you want to flex your architecture muscles with the [IoC Container](/docs/ioc). The choice is yours!
0 # Laravel быстрый старт

- [Установка](#installation)
- [Роутинг](#routing)
- [Создание представления](#creating-a-view)
- [Создание миграций](#creating-a-migration)
- [Eloquent ORM](#eloquent-orm)
- [Отображение данных](#displaying-data)

<a name="installation"></a>
## Установка

Для установки Laravel фреймворка, скачайте копию [репозитория с Github](https://github.com/laravel/laravel/archive/master.zip). Далее, после [установки Composer](http://getcomposer.org), выполните команду "composer install" в корневой директории проекта. Эта команда скачает и установит все зависимости фреймворка.

Также вы можете установить Laravel, выполнив следующую команду в терминале:

composer create-project laravel/laravel

После установки фреймворка, посмотрите на проект и хорошо ознакомьтесь со структурой директорий. В директории "app" находятся такие как "views", "controllers" и "models". Большая часть кода вашего приложения будет находится в этой директории. Также вы можете изучить директорию "app/config" и параметры конфигурации, доступные вам.

<a name="routing"></a>
## Роутинг

Для начала, давайте создадим наш первый роут. В Laravel самый простой роут - это анонимная функция или замыкание. Откройте файл "app/routes.php" и добавьте в конце:

Route::get('users', function()
{
return 'Пользователи!';
});

Теперь, если вы перейдете в браузере по ссылке "/users", то вы должны увидеть в ответ "Пользователи!". Отлично! Вы только что создали первый роут.

Роуты также можно связать с классом контроллером. Например:

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

Этот роут говорит фреймворку, что запрос на роут "/users" должен вызвать метод "getIndex" класса "UserController". Более подробную информацию о роутах контроллеров, можно прочитать в [документации по контроллерам](/docs/controllers).

<a name="creating-a-view"></a>
## Создаем представление

Дальше мы создадим простое представление для отображения пользовательских данных. Представления находятся в директории "app/views" и содеражт HTML-код нашего приложения. Мы собираемся добавить два новых представления в эту директорию: "layout.blade.php"и "users.blade.php". Давайте сначала добавим файл "layout.blade.php":

<html>
<body>
<h1>Laravel быстрый старт</h1>

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

Затем добавим представление "users.blade.php":

@extends('layout')

@section('content')
Пользователи!
@stop

Скорее всего некоторый синтаксис выглядит необычно. Это потому, что мы используем шаблонизатор из Laravel, который называется Blade. Blade - очень юыстрый, потому что это просто набор регулярных выражений, которые обрабатывают ваши шаблоны, чтобы сделать из них чистый PHP код. Blade обеспечивает мощную функциональность, такую как наследование шаблонов, а также некоторый синтаксис замешанный на обычных управляющих конструкциях PHP таких как "if" и "for". Для более детального рассмотрения читайте [документацию по Blade](/docs/templates).

Теперь, когда у нас есть представления, давайте вернем их через наш роут "/users". Вместо того, чтобы возвращать "Пользователи!" из роута, вернем представление:

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

Замечательно! Теперь мы установили простое представление, которое расширяет разметку. Далее давайте начнем работать с нашей базой данных.

<a name="creating-a-migration"></a>
## Создание миграций

Для создания таблицы, где будут хранится наши данные, мы будем использовать миграции. Миграции позволяют выразительно определять изменения в ваше базе данных и легко делится ими с остальной командой.

Во-первых, давайте настроим соединение с базой данных. Вы можете настроить все, что связано с базой данных в файле "app/config/database.php". По умолчанию Laravel настроен на использование SQLite и SQLite база данных включена в директории "app/database". Если вы желаете, то можете изменить параметр "drive" на "mysql" и настроить параметры доступа для соеднинения с базой "mysql".

Далее, для создания миграций, будем использовать [Artisan CLI](/docs/artisan). В корневой директории вашего проекта запустите следующую команду в терминале:

php artisan migrate:make create_users_table

Затем, найдите сгенерированный файл миграции в директории "app/database/migrations". Этот файл содержит класс с двумя методами "up" и "down". В методе "up" следует сделать желаемые изменения таблицы в базе данных, а в методе "down" вы легко можете откатить их.

Давайте определим миграцию, которая выш=глядит как:

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');
}

→# Introduction

- [Laravel Philosophy](#laravel-philosophy)
- [Learning Laravel](#learning-laravel)
- [Development Team](#development-team)

<a name="laravel-philosophy"></a>
## Laravel Philosophy

Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable, creative experience to be truly fulfilling. Laravel attempts to take the pain out of development by easing common tasks used in the majority of web projects, such as authentication, routing, sessions, and caching.

Laravel aims to make the development process a pleasing one for the developer without sacrificing application functionality. Happy developers make the best code. To this end, we've attempted to combine the very best of what we have seen in other web frameworks, including frameworks implemented in other languages, such as Ruby on Rails, ASP.NET MVC, and Sinatra.

Laravel is accessible, yet powerful, providing powerful tools needed for large, robust applications. A superb inversion of control container, expressive migration system, and tightly integrated unit testing support give you the tools you need to build any application with which you are tasked.

<a name="learning-laravel"></a>
## Learning Laravel

One of the best ways to learn Laravel is to read through the entirety of its documentation. This guide details all aspects of the framework and how to apply them to your application.

In addition to this guide, you may wish to check out some [Laravel books](http://wiki.laravel.io/Books). These community written books serve as a good supplemental resource for learning about the framework:

- [Code Bright](https://leanpub.com/codebright) by Dayle Rees
- [Laravel Testing Decoded](https://leanpub.com/laravel-testing-decoded) by Jeffrey Way

<a name="development-team"></a>
## Development Team

Laravel was created by [Taylor Otwell](https://github.com/taylorotwell), who continues to lead development of the framework. Other prominent community members and contributors include [Dayle Rees](https://github.com/daylerees), [Shawn McCool](https://github.com/ShawnMcCool), [Jeffrey Way](https://github.com/JeffreyWay), [Jason Lewis](https://github.com/jasonlewis), [Ben Corlett](https://github.com/bencorlett), [Franz Liedke](https://github.com/franzliedke), [Dries Vints](https://github.com/driesvints), [Mior Muhammed Zaki](https://github.com/crynobone), and [Phil Sturgeon](https://github.com/philsturgeon).
0 # Введение

- [Философия Laravel](#laravel-philosophy)
- [Изучение Laravel](#learning-laravel)
- [Команда разработки](#development-team)
- [Спонсоры фреймворка](#framework-sponsors)

<a name="laravel-philosophy"></a>
## Философия Laravel

Laravel - это фреймворк для разработки веб-приложений с выразительным и изящным синтаксисом. Мы верим, что разработка должна быть приятной, творческой, приносящей удовольствие. Laravel старается взять на себя страдания разработчика и упростить общие задачи, которые встречаются в большинстве веб-проектах, такие как аутентификация, роутинг, сессии и кэширование.

Laravel нацелен на то, чтобы сделать процесс разработки приятным для разработчика, не жертвуя функциональностью приложения. Счастливые разработчики пишут самый лучший код. Для этого, мы попытались объединить то самое лучшее, что видели в других фреймворках, включая фреймворки, написанные на других языках, такие как Ruby on Rails, ASP.NET и Sinatra.

Laravel - понятный, но мощный, представляющий мощные инструменты, необходимые для больших, надежных приложений. Прекрасный контейнер инверсии управления, выразительная система миграций и тесно интегрированная поддержка unit-тестов, дают тебе инструменты необходимые для создания любого приложения, над которым ты работаешь.

<a name="learning-laravel"></a>
## Изучение Laravel

Один из самых лучших способов изучить Laravel - это полностью прочитать данную документацию. Это руководство детально рассматривает все аспекты фреймворка и то, как их использовать в твоем приложении.

В дополнение к данному руководству, возможно ты захочешь посмотреть на некоторые [книги по Laravel](http://wiki.laravel.io/Books). Эти книги, написанные сообществом, послужат хорошим дополнительным источником для изучения фреймворка.

- [Code Bright](https://leanpub.com/codebright) Дейла Риса
- [Laravel Testing Decoded](https://leanpub.com/laravel-testing-decoded) Джеффри Уэйа

<a name="development-team"></a>
## Команда разработки

Laravel был создан [Тэйлором Отуеллом](https://github.com/taylorotwell), который продолжает руководить разработкой фреймворка. Другие известные члены сообщества и участники: [Дэйл Рис](https://github.com/daylerees), [Шон МакКул](https://github.com/ShawnMcCool), [Джеффри Уэй](https://github.com/JeffreyWay), [Джейсон Льюис](https://github.com/jasonlewis), [Бен Корлетт](https://github.com/bencorlett), [Франз Лидк](https://github.com/franzliedke), [Драйс Винтс](https://github.com/driesvints), [Миор Мухамед Заки](https://github.com/crynobone) и [Фил Стерджен](https://github.com/philsturgeon).

<a name="framework-sponsors"></a>
## Спонсоры фреймворка

Следующие организации оказали финансовую поддержку для разработки фреймворка Laravel:

- [UserScape](http://userscape.com)
- [Cartalyst](http://cartalyst.com)
- [Elli Davis - Toronto Realtor](http://ellidavis.com)
- [Jay Banks - Vancouver Lofts & Condos](http://jaybanks.ca/vancouver-lofts-condos)
- [Julie Kinnear - Toronto MLS](http://juliekinnear.com/toronoto-mls-listings)
- [Jamie Sarner - Toronto Real Estate](http://jamiesarner.com)
Резюме
Пол:
мужчина
Родной язык:
русский
С нами:
с 7 июня 2013 г. (4880 дней)
Не является членом клуба.
Деятельность:
2 версии перевода с общим рейтингом 0
Написать johnroyzreit личное сообщение