Laravel Code Tips #2

Bayram EKER
2 min readSep 19, 2022

--

1-) Find

// You can specify the columns you need// in when you use the find method on a modelUser::find(‘id’, [‘email’,’name’]);
// You can increment or decrement // a field in your model
// Increment or decrement by oneProduct::find($productId)->increment(‘views’);Product::find($productId)->decrement(‘views’);// You can also specify an amountProduct::find($productId)->increment(‘views’, 5);Product::find($productId)->decrement(‘views’, 5);

2-) Swap

Str::macro(‘swap’, function($map, $subject){ return str_replace(array_keys($map), array_values($map), $subject);});$subject= ‘This post created by Bayram ek’;echo Str::swap([‘post’ => ‘code’,‘ek’ => ‘Eker’], $subject);// This code created by Bayram Eker

3-) Foreach $loop

foreach($users as $user){if($loop->first){// This is the first iteration}if($loop->last){// This is the last iteration}}

4-) Controller route groups

Route::controller(OrderController::class)->group(function () {   Route::get(‘/orders/{id}’, ‘show’);   Route::post(‘/orders’, ‘store’);});

Bonus: Checked and Selected

// Checkbox
<input type=”Checkbox”
name=”active”
value=”active”
@checked(old(‘avctive’, $user->active)) />
// Select
<select name=”version”>
@foreach ($prdoct->versions as $version)
<option value=”{{ $version }}” @selected(old(‘version’) == $version>
{{ $version }}
</option>
@endforeach
</select>

Thank you for reading this article.

If you find this article useful please kindly share it with your network and feel free to use the comment section for questions, answers, and contributions.

You might also like :

--

--

Responses (2)