📜 ⬆️ ⬇️

25 Laravel Tips and Tricks

There was a time, quite recently, when PHP and its community hated. The main joke was how awful PHP is.

Yes, unfortunately, the community and the ecosystem were simply lower than the communities of other modern languages ​​by level. It seemed that the purpose of PHP was to live most of the time in the form of messy WordPress themes.

But later, surprisingly, things began to change - and quickly enough. As if while the witch was stirring the pot, innovative projects began to appear out of nowhere. Probably the most notable project was Composer: the most complete dependency manager for PHP (like Bundler for Ruby or NPM for Node.js). In the past, PHP developers were forced to cope with PEAR (which was a terrible dream, in fact), now, thanks to Composer, they can simply update the JSON file, and immediately pull up all the necessary dependencies. Here is a profiler, there is a framework for testing. It takes seconds.

In the crowded world of PHP frameworks, just when CodeIgniter began to run out of steam, the Laravel Taylor Otvell framework arose from the ashes to become the darling of society. With such a simple and elegant syntax, creating applications with Laravel and PHP was absolute fun! Further, with the fourth version of the framework, which fully used Composer, it finally seemed that for the community all things fall into place.
')
image

Want to migrate (version control database)? Made by How about a powerful implementation of Active Record? Of course, Eloquent will do everything for you. How about being able to test? Of course! Routing (routing)? By all means! What about a well-tested HTTP layer? Thanks to Composer, Laravel uses many excellent symfony components. When it comes to business, there is every chance that Laravel can already offer it to you!

image

Previously, PHP was similar to the game Genga - in one cube from falling apart - suddenly, thanks to Laravel and Composer, a light came on at the end of the tunnel. So remove all the hints, and let's rummage in everything that the framework has to offer!

1. Eloquent requests *


Laravel offers one of the most powerful implementations of Active Record in the PHP world. Let's say you have an orders table along with an Eloquent Order model.
class Order extends Eloquent {}

, PHP. SQL. .
Order::all();

! , , . :
$orders = Order::orderBy('release_date', 'desc')->get();

, , . , , .
$order = new Order;
$order->title = 'Xbox One';
$order->save();

! Laravel, , , .

* — Eloquent — Active Record Laravel, .

2. ()


Laravel , . Sinatra ? Laravel ,
Route::get('orders', function()
{
    return View::make('orders.index')
        ->with('orders', Order::all());
});

API, , . , Laravel .
Route::get('orders', 'OrdersController@index');

! , Laravel ? — , .

3.


, ? , . Laravel? , , Eloquent .
class Task extends Eloquent {
    public function user()
    {
        return $this->belongsTo('User');
    }
}

class User extends Eloquent {
    public function tasks()
    {
        return $this->hasMany('Task');
    }
}

! id = 1. 2 .
$user = User::find(1);
$tasks = $user->tasks;

, , , , .
$task = Task::find(1);
$user = $task->user;


4.


, . — - . , .
{{ Form::model($order) }}
    <div>
        {{ Form::label('title', 'Title:') }}
        {{ Form::text('title') }}
    </div>
 
    <div>
        {{ Form::label('description', 'Description:') }}
        {{ Form::textarea('description') }}
    </div>
{{ Form::close() }}

Order, . !

5.


, , . , Laravel , .

, , .
$questions = Question::remember(60)->get();

! , , , .

6.


, . — , .
, Laravel (), .
View::composer('layouts.nav', function($view)
{
    $view->with('tags', ['tag1', 'tag2']);
});

, , layouts/nav.blade.php, ( ) $tags.

7.


Laravel . , , , , Auth::attempt(). , users, .
$user = [
    'email' => 'email',
    'password' => 'password'
];
 
if (Auth::attempt($user))
{
    //  
}

, /logout URI?
Route::get('logout', function()
{
    Auth::logout();
     
    return Redirect::home();
});


8.


RESTfully Laravel ! , Route::resource() .
Route::resource('orders', 'OrdersController');

8 .



, OrdersController :

php artisan controller:make OrdersController

, , . , /orders index, /orders/create — create .

, RESTful API.

9. Blade


, PHP , . , . Laravel Blade, . .blade.php, . :
@if ($orders->count())
    <ul>
        @foreach($orders as $order)
            <li>{{ $order->title }}</li>
        @endforeach
    </ul>
@endif


10.


Laravel Composer, PHPUnit “ ”. phpunit , .

Laravel

, 200.
public function test_home_page()
{
    $this->call('GET', '/');
    $this->assertResponseOk();
}

, , , , , .
public function test_contact_page_redirects_user_to_home_page()
{
    $postData = [
        'name' => 'Joe Example',
        'email' => 'email-address',
        'message' => 'I love your website'
    ];
 
    $this->call('POST', '/contact', $postData);
 
    $this->assertRedirectedToRoute('home', null, ['flash_message']);
}


11. “ ”


Laravel 4.1, 2013, Artisan, SSH . SSH :
SSH::into('production')->run([
    'cd /var/www',
    'git pull origin master'
]);

run() , Laravel ! , Artisan , php artisan command:make DeployCommand fire() .

12.


Laravel Observer, . , , illuminate.query, .

.
Event::listen('user.signUp', function()
{
    //  ,  ,
    //   
});

Laravel, , , . Laravel , IoC .
Event::listen('user.signUp', 'UserEventHandler');


13.


image

, , . , routes.php (, ).

Laravel routes, , , .
php artisan routes


14.


, . , . , , , . , .

, , ?
Queue::push('SignUpService', compact('user'));

, , , Laravel Iron.io “push” . , , . php artisan queue:subscribe, Iron.io , . .
image

15.


, Laravel ! Validator . make, Laravel .
$order = [
    'title' => 'Wii U',
    'description' => 'Game console from Nintendo'
];
 
$rules = [
    'title' => 'required',
    'description' => 'required'
];
 
$validator = Validator::make($order, $rules);
 
if ($validator->fails())
{
    var_dump($validator->messages()); // validation errors array
}



16. Tinker


image

, Laravel , . tinker .

Tinker Boris.

$ php artisan tinker

> $order = Order::find(1);
> var_dump($order->toArray());
> array(...)


17.


, . , “” , , , . , , php artisan migrate, .

users, :
php artisan migrate:make create_users_table

, , . , php artisan migrate . ! ? ! php artisan migrate:rollback.

.
public function up()
{
    Schema::create('faqs', function(Blueprint $table) {
        $table->integer('id', true);
        $table->text('question');
        $table->text('answer');
        $table->timestamps();
    });
}
 
public function down()
{
    Schema::drop('faqs');
}

, drop() up(). , “” . , , SQL?

18.


Laravel . , “Laravel 4 Generators”, . , , pivot .

. , :

php artisan generate:migration create_users_table --fields="username:string, password:string"


. .
Laravel 4 Generators Composer.

19.


, . , , .

, Laravel .
php artisan command:make MyCustomCommand

. , app/commands/MyCustomCommand.php, .
protected $name = 'command:name';
protected $description = 'Command description.';

, fire() . Artisan, app/start/artisan.php.
Artisan::add(new MyCustomCommand);

, , ! .

20.


Laravel . “” , , , (Route::get(), Config::get(), ), .

“ ” IoC , “” . :
Validator::shouldReceive('make')->once();

, shouldReceive . “ ”, Laravel Mockery. , , .

21.


, Laravel, , “ ”, . :
{{ Form::open() }}
    {{ Form::text('name') }}
    {{ Form::textarea('bio') }}
    {{ Form::selectYear('dob', date('Y') - 80, date('Y')) }}
{{ Form::close() }}

? Laravel !

22. IoC (Inverse of control)


Laravel IoC , , . , .

typehint , Laravel, PHP Reflection API, .
public function __construct(MyDependency $thing)
{
    $this->thing = $thing;
}

IoC , .
$myClass = App::make('MyClass');

, IoC . typehint , Laravel .

23.


. , — ! , , . .

. dev API. .

, Laravel . bootstrap/start.php.

local , hostname .
$env = $app->detectEnvironment(array(

	'local' => array('your-machine-name'),

));

, . . , Laravel! detectEnvironment.
$env = $app->detectEnvironment(function()
{
    return getenv('ENV_NAME') ?: 'local';
});

, ( ), local.

24.


Laravel . app/config , , , . , API dev .
<?php // app/config/development/billing.php
 
return [
    'api_key' => 'your-development-mode-api-key'
];

. Config::get(‘billing.api_key’) Laravel , .

25.


, Laravel , . , , Laravel.

Source: https://habr.com/ru/post/222453/


All Articles