shareit/app/Http/Controllers/HomeController.php

82 lines
2.0 KiB
PHP
Raw Permalink Normal View History

2018-09-09 04:03:41 +00:00
<?php
namespace App\Http\Controllers;
use \App\User;
2018-09-09 04:03:41 +00:00
class HomeController extends Controller
{
protected $activeUsers = [];
2018-09-09 04:03:41 +00:00
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
2018-09-21 03:42:19 +00:00
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$items = User::loggedIn()->items()->with('users')->get();
$numberOfUsedItems = 0;
foreach ($items as $item) {
if (isset($item->used_by)) {
$numberOfUsedItems++;
}
$this->getUsername($item->users, $item->used_by);
$this->getUsername($item->users, $item->waiting_user_id);
}
$products = $items
->sortBy('product.name', SORT_NATURAL | SORT_FLAG_CASE)
->groupBy('product.name');
return view(
2021-05-20 23:37:35 +00:00
'home',
['products' => $products, 'users' => $this->activeUsers, 'usedItems' => $numberOfUsedItems]
);
}
2018-09-21 03:42:19 +00:00
/**
* Get the username from an specified user id.
2021-05-20 23:37:35 +00:00
*
* @param object $itemUsers Array with IDs and usernames
* @param int $id The user id to search for
2018-09-21 03:42:19 +00:00
*
* @return void
2018-09-21 03:42:19 +00:00
*/
protected function getUsername(\Illuminate\Database\Eloquent\Collection $itemUsers, ?int $id)
2018-09-21 03:42:19 +00:00
{
if ($id && !isset($this->activeUsers[$id])) {
$this->activeUsers[$id] = $this->findName($itemUsers, $id);
}
2018-09-21 03:42:19 +00:00
}
2018-09-09 04:03:41 +00:00
/**
* Get a name from a specific id in a array
2018-09-09 04:03:41 +00:00
*
* @param array $array The array of objects with ID and Names
* @param int $id The ID of the user
*
* @return string The username of the specified id
2018-09-09 04:03:41 +00:00
*/
protected function findName($array, $id)
2018-09-09 04:03:41 +00:00
{
foreach ($array as $object) {
if ($object->id == $id) {
return $object->name;
}
}
2018-09-09 04:03:41 +00:00
}
}