Laravel Tips and Tricks #2

Bayram EKER
2 min readSep 14, 2022

--

Important notes

First of all, I am writing the information here for myself. But anyone can come and have a look.

1-) Nested Foreach and Nested Map

Map :

$result->children->map(function ($item) {
// do some stuff with $item or you can no map through its children
$item->children->map(function ($nestedItem) {
// do some stuff with $nestedItem etc//
});
});

Foreach :

view

@foreach ($result as $children)
@foreach ($children->posts as $nestedItem)

@endforeach
@endforeach

controller

foreach($result as $children){
foreach($children->posts as $nestedItem){
}
}

2-) HTTP Client

Let’s say we send api request with curl and your code is as follows:

$veri = json_encode($veri);
$ch = curl_init($moka_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $veri);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(‘Content-Type:application/json’));
curl_setopt($ch, CURLOPT_SSLVERSION, 6); // TLS 1.2 baglanti destegi icin
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // VerifyPeer = 0 kalmalı
$result = curl_exec ($ch);
curl_close ($ch);
$result = json_decode($result);

If we use HTTP Client instead, we can get the job done with just one line of code :

$result = Http::accept('Content-Type:application/json')
->post($moka_url,$veri);

3-) Scope for keyword search

Model file :

public function scopeWhereFilters($query, array $filters)
{
$filters = collect($filters);

$query->when($filters->get('keyword'), function ($query, $search) {
$query->whereKeyword($search);
});
}

And

public function scopeWhereKeyword($query, $keyword)
{
foreach (explode(' ', $keyword) as $term) {
$query->where(function ($query) use ($term) {
$query->where('order_no', 'like', '%' . $term . '%')
->orWhere('order_name', 'like', '%' . $term . '%')
->orWhere('barcode', 'like', '%' . $term . '%')
->orWhere('product_name', 'like', '%' . $term . '%')

->WhereHas('user', function ($t2) use ($term) {
$t2->Where('name', 'like', '%' . $term . '%');
$t2->orWhere('email', 'like', '%' . $term . '%');
});
});
}
}

Eloquent query: (in controller)

$orders = Order::with(['product'])
->whereFilters($request->only('keyword'))
->where('order_status', 1)
->orderBy('id', 'asc')
->get();

Note : route type must be get

Bonus : Add Artisan Commands to Panel

Routes.php:

Route::group([
‘middleware’ => [‘auth’, ‘role:superadmin’, ‘verified’]
], function () {
Route::get(‘cache-clear’, function () {
\Artisan::call(‘cache:clear’);
return redirect(‘/admin/home’)->with(‘success’, Artisan::output());
});
Route::get(‘optimize-clear’, function () {
\Artisan::call(‘optimize:clear’);
return redirect(‘/admin/home’)->with(‘success’, Artisan::output());
});
Route::get(‘optimize’, function () {
\Artisan::call(‘optimize’);
return redirect(‘/admin/home’)->with(‘success’, Artisan::output());
});
});

--

--