• Czas czytania ~2 min
  • 26.05.2023

Większość z nich jest prawdopodobnie powszechnie znana, ale zapisuję bloki kodu, których wiem, że nie będę często używać i o których zapomnę. Od czasu do czasu przeglądam je, aby odświeżyć pamięć.

Oto 15 fragmentów / metod Laravel, które znalazłem przewijając moje SnippetsLab:

1. Ustalenie, czy rekord na firstOrCreate był nowy, czy nie

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

2. Znajdowanie powiązanych identyfikatorów w relacji

$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. Klucze

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

modelu 5. throw_if()

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

6. Zrzuć wszystkie kolumny tabeli

Schema::getColumnListing('table')

7. Przekieruj do domen

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

zewnętrznych 8. Request exists() vs has()Pomocnik 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

Pomocnik optional()

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

Pomocnik optional()

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

Pomocnik 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) {
    // ..
}

umożliwia dostęp do właściwości lub wywoływanie metod obiektu. Jeśli dany obiekt ma wartość null, właściwości i metody zwrócą null zamiast powodować błąd.

// 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()Pomocnik data_get()

umożliwia pobranie wartości z tablicy lub obiektu z notacją kropkową. Działa to podobnie do array_get(). Opcjonalny trzeci parametr może służyć do podania wartości domyślnej, jeśli klucz nie zostanie znaleziony.

$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()

Model i odpowiadające mu relacje można zapisać za pomocą metody 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

O

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...

O autorze CrazyBoy49z
WORK EXPERIENCE
Kontakt
Ukraine, Lutsk
+380979856297