Wednesday, August 22, 2018

PHP Foreach Key by Pointer


Here is a way to add a new elements to a new array in PHP foreach function, by reference on a new element.


$items = Item::get();
$formattedItems = [];

foreach ($items as $item) {
    $fm = &$formattedItems[];
    $fm['id'] = $item->id;
    $fm['label'] = $item->label;
    $fm['icon'] = $item->icon;
}


var_dump($formattedItems);


Simple and clean.

Get Service Instance Anywhere in Laravel

Inject Service Instance by Constructor


Code Example:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class MyController extends Controller
{
    protected $client;

    public function __construct(Client $client)
    {
        $this->client = $client;
    }

    public function store(Request $request)
    {
        $response = $this->client->message()->send([
            'text' => $request->input('text'),
        ]);
    }
}