• Время чтения ~2 мин
  • 26.05.2023

Большинство из них, вероятно, общеизвестны, но я записываю блоки кода, которые, как я знаю, я не буду использовать часто и забуду о них. Время от времени я просматриваю их, чтобы освежить память.

Вот 15 фрагментов/методов Laravel, которые я нашел, просматривая свою лабораторию SnippetsLab:

1. Определение того, была ли запись в firstOrCreate новой или нет

$product = Product::firstOrCreate(...)
if ($product->wasRecentlyCreated()) {
    // New product
} else {
    // Existing product
}

2. Поиск связанных идентификаторов в связи

$user->roles()->allRelatedIds()->toArray();

BelongsToMany 3. abort_unless()

// Instead of
public function show($item) {
    if (// User can not do this thing) {
        return false;
    }
    
    // Else do this
}
// Do this
public function show($item) {
    abort_unless(Gate::allows('do-thing', $item), 403);
    
    // Actual logic
}
// Another use case, make sure the user is logged in
abort_unless(Auth::check(), 403);

4. Модельные ключи

User::all()->pluck('id')->toArray();
// In most cases, however, this can be shortened. Like this:
User::all()->modelKeys();

5. throw_if()

throw_if(
    !Hash::check($data['current_password'], $user->password),
    new Exception(__('That is not your old password.'))
);

6. Дамп всех столбцов таблицы

Schema::getColumnListing('table')

7. Редирект на внешние домены

return redirect()->away('https://www.google.com');

8. Запрос exists() vs has()Вспомогательный элемент optional()

// http://example.com?popular
$request->exists('popular') // true
$request->has('popular') // false
http://example.com?popular=foo
$request->exists('popular') // true
$request->has('popular') // true

Вспомогательный элемент optional()

// From
@if (isset($records))
    // $records is defined and is not null
@endif
// To
@isset($records)
    // $records is defined and is not null
@endisset

Вспомогательный элемент optional()

// From
@if (empty($records))
    // $records is "empty"
@endif
// To
@empty($records)
    // $records is "empty"
@endempty

Вспомогательный элемент optional()

// From
@if ($users->count())
    @foreach ($users as $user)
    
    @endforeach
@else
@endif
// To
@forelse ($users as $user)
    {{ $user->name }}
@empty
    <p>No Users</p>
@endforelse

$posts = is_array($posts) ? $posts : [$posts];
// Same as
$posts = array_wrap($posts);
// Inline
foreach (array_wrap($posts) as $post) {
    // ..
}

Вспомогательный элемент optional()

позволяет получить доступ к свойствам или вызвать методы объекта. Если данный объект равен null, свойства и методы будут возвращать null вместо того, чтобы вызывать ошибку.

// User 1 exists, with account
$user1 = User::find(1);
$accountId = $user1->account->id; // 123
// User 2 exists, without account
$user2 = User::find(2);
$accountId = $user2->account->id; // PHP Error: Trying to get property of non-object
// Fix without optional()
$accountId = $user2->account ? $user2->account->id : null; // null
$accountId = $user2->account->id ?? null; // null
// Fix with optional()
$accountId = optional($user2->account)->id; // null

14. data_get()Помощник data_get()

позволяет получить значение из массива или объекта с точечной нотацией. Это также работает аналогично array_get(). Необязательный третий параметр можно использовать для ввода значения по умолчанию, если ключ не найден.

$array = ['albums' => ['rock' => ['count' => 75]]];
$count = data_get($array, 'albums.rock.count'); // 75
$avgCost = data_get($array, 'albums.rock.avg_cost', 0); // 0
$object->albums->rock->count = 75;
$count = data_get($object, 'albums.rock.count'); // 75
$avgCost = data_get($object, 'albums.rock.avg_cost', 0); // 0

15. push()

Вы можете сохранить модель и соответствующие ей связи с помощью метода push().

$user = User::first();
$user->name = "Peter";
$user->phone->number = '1234567890';
$user->push(); // This will update both user and phone record in DB

Comments

No comments yet
Yurij Finiv

Yurij Finiv

Full stack

Про мене

Professional Fullstack Developer with extensive experience in website and desktop application development. Proficient in a wide range of tools and technologies, including Bootstrap, Tailwind, HTML5, CSS3, PUG, JavaScript, Alpine.js, jQuery, PHP, MODX, and Node.js. Skilled in website development using Symfony, MODX, and Laravel. Experience: Contributed to the development and translation of MODX3 i...

Об авторе CrazyBoy49z
WORK EXPERIENCE
Контакты
Ukraine, Lutsk
+380979856297