У меня есть данные в массиве, и я должен показать в Laravel шаблоне блейда, но он показывает ошибку при попытке получить имя - PullRequest
0 голосов
/ 03 мая 2020

Мне нужно получить все названия организаций без использования l oop, потому что я не могу два цикла. Что я пытаюсь в Blade:

<?php $number = 0; $org_names_counter = 0;?>
@foreach($managers as $items)
    {{--  @foreach($org_names as $key => $org_name) --}}

    <?php $number++; ?>
    <tr>
        <td>{{$number}}</td>
        <td>{{$items->name}}</td>
        <td>{{$items->email}}</td>
        <td> <?php echo $org_names[$org_names_counter]['name']; ?> </td>
        <td>
            <a href='editmanagers/{{ $items->id }}' class="edit" title="Edit" data-toggle="tooltip">
                <i class="material-icons">&#xE254;</i>
            </a>
            <a href='deletemanagers/{{ $items->id }}' class="delete" title="Delete" data-toggle="tooltip">
                <i class="material-icons">&#xE872;</i>
            </a>
        </td>
    </tr>
@endforeach

Это код моего контроллера:

public function managersdata()
{
    if (Auth::user()->role == "admin") {
        $org_names = [];
        $data = Managers::where('role', 'managers')->get();
        foreach ($data as $datas) {
            $org_names[] = Organization::where('id', $datas->organization_id)->get();
        }
        $managers = Managers::where('role', 'managers')->get();

        return view('users.managersdetails', compact('managers', 'org_names'));
    }
}

Я получаю эту ошибку:

Неопределенный индекс: имя (Просмотр: /Applications/XAMPP/xamppfiles/htdocs/EASI/resources/views/users/managersdetails.blade.php)

И вот такой вывод я получаю:

Array ( [0] => Illuminate\Database\Eloquent\Collection Object ( [items:protected] => Array ( [0] => App\Organization Object ( [table:protected] => organization [primaryKey] => id [timestamps] => [fillable:protected] => Array ( [0] => name [1] => email [2] => city ) [connection:protected] => mysql [keyType:protected] => int [incrementing] => 1 [with:protected] => Array ( ) [withCount:protected] => Array ( ) [perPage:protected] => 15 [exists] => 1 [wasRecentlyCreated] => [attributes:protected] => Array ( [id] => 2 [name] => test 4 [email] => test@gmail.com [city] => jhgkjhk ) [original:protected] => Array ( [id] => 2 [name] => test 4 [email] => test@gmail.com [city] => jhgkjhk ) [changes:protected] => Array ( ) [casts:protected] => Array ( ) [classCastCache:protected] => Array ( ) [dates:protected] => Array ( ) [dateFormat:protected] => [appends:protected] => Array ( ) [dispatchesEvents:protected] => Array ( ) [observables:protected] => Array ( ) [relations:protected] => Array ( ) [touches:protected] => Array ( ) [hidden:protected] => Array ( ) [visible:protected] => Array ( ) [guarded:protected] => Array ( [0] => * ) ) ) ) [1] => Illuminate\Database\Eloquent\Collection Object ( [items:protected] => Array ( [0] => App\Organization Object ( [table:protected] => organization [primaryKey] => id [timestamps] => [fillable:protected] => Array ( [0] => name [1] => email [2] => city ) [connection:protected] => mysql [keyType:protected] => int [incrementing] => 1 [with:protected] => Array ( ) [withCount:protected] => Array ( ) [perPage:protected] => 15 [exists] => 1 [wasRecentlyCreated] => [attributes:protected] => Array ( [id] => 5 [name] => test1 [email] => test1@gmail.com [city] => test ) [original:protected] => Array ( [id] => 5 [name] => test1 [email] => test1@gmail.com [city] => test ) [changes:protected] => Array ( ) [casts:protected] => Array ( ) [classCastCache:protected] => Array ( ) [dates:protected] => Array ( ) [dateFormat:protected] => [appends:protected] => Array ( ) [dispatchesEvents:protected] => Array ( ) [observables:protected] => Array ( ) [relations:protected] => Array ( ) [touches:protected] => Array ( ) [hidden:protected] => Array ( ) [visible:protected] => Array ( ) [guarded:protected] => Array ( [0] => * ) ) ) ) [2] => Illuminate\Database\Eloquent\Collection Object ( [items:protected] => Array ( [0] => App\Organization Object ( [table:protected] => organization [primaryKey] => id [timestamps] => [fillable:protected] => Array ( [0] => name [1] => email [2] => city ) [connection:protected] => mysql [keyType:protected] => int [incrementing] => 1 [with:protected] => Array ( ) [withCount:protected] => Array ( ) [perPage:protected] => 15 [exists] => 1 [wasRecentlyCreated] => [attributes:protected] => Array ( [id] => 3 [name] => test 2 [email] => test@gmail.com [city] => hhhhhhhhhhh ) [original:protected] => Array ( [id] => 3 [name] => test 2 [email] => test@gmail.com [city] => hhhhhhhhhhh ) [changes:protected] => Array ( ) [casts:protected] => Array ( ) [classCastCache:protected] => Array ( ) [dates:protected] => Array ( ) [dateFormat:protected] => [appends:protected] => Array ( ) [dispatchesEvents:protected] => Array ( ) [observables:protected] => Array ( ) [relations:protected] => Array ( ) [touches:protected] => Array ( ) [hidden:protected] => Array ( ) [visible:protected] => Array ( ) [guarded:protected] => Array ( [0] => * ) ) ) ) [3] => Illuminate\Database\Eloquent\Collection Object ( [items:protected] => Array ( [0] => App\Organization Object ( [table:protected] => organization [primaryKey] => id [timestamps] => [fillable:protected] => Array ( [0] => name [1] => email [2] => city ) [connection:protected] => mysql [keyType:protected] => int [incrementing] => 1 [with:protected] => Array ( ) [withCount:protected] => Array ( ) [perPage:protected] => 15 [exists] => 1 [wasRecentlyCreated] => [attributes:protected] => Array ( [id] => 2 [name] => test 4 [email] => test@gmail.com [city] => jhgkjhk ) [original:protected] => Array ( [id] => 2 [name] => test 4 [email] => test@gmail.com [city] => jhgkjhk ) [changes:protected] => Array ( ) [casts:protected] => Array ( ) [classCastCache:protected] => Array ( ) [dates:protected] => Array ( ) [dateFormat:protected] => [appends:protected] => Array ( ) [dispatchesEvents:protected] => Array ( ) [observables:protected] => Array ( ) [relations:protected] => Array ( ) [touches:protected] => Array ( ) [hidden:protected] => Array ( ) [visible:protected] => Array ( ) [guarded:protected] => Array ( [0] => * ) ) ) ) [4] => Illuminate\Database\Eloquent\Collection Object ( [items:protected] => Array ( [0] => App\Organization Object ( [table:protected] => organization [primaryKey] => id [timestamps] => [fillable:protected] => Array ( [0] => name [1] => email [2] => city ) [connection:protected] => mysql [keyType:protected] => int [incrementing] => 1 [with:protected] => Array ( ) [withCount:protected] => Array ( ) [perPage:protected] => 15 [exists] => 1 [wasRecentlyCreated] => [attributes:protected] => Array ( [id] => 2 [name] => test 4 [email] => test@gmail.com [city] => jhgkjhk ) [original:protected] => Array ( [id] => 2 [name] => test 4 [email] => test@gmail.com [city] => jhgkjhk ) [changes:protected] => Array ( ) [casts:protected] => Array ( ) [classCastCache:protected] => Array ( ) [dates:protected] => Array ( ) [dateFormat:protected] => [appends:protected] => Array ( ) [dispatchesEvents:protected] => Array ( ) [observables:protected] => Array ( ) [relations:protected] => Array ( ) [touches:protected] => Array ( ) [hidden:protected] => Array ( ) [visible:protected] => Array ( ) [guarded:protected] => Array ( [0] => * ) ) ) ) ) 

enter image description here

1 Ответ

0 голосов
/ 04 мая 2020

Ошибка, которую вы видите:

Неопределенное имя индекса

Сообщает нам, что это строка проблемы:

echo $org_names[$org_names_counter]['name'];

Глядя на код контроллера, эта переменная устанавливается с помощью:

$org_names[] = Organization::where('id', $datas->organization_id)->get();

Метод Eloquent get() вернет коллекцию , поэтому $org_names представляет собой массив коллекции. $org_names[0] - это коллекция из Organization с, а не один Organization.

Вы также можете увидеть это в показанном вами дампе:

Array (
    [0] => Illuminate\\Database\\Eloquent\\Collection Object (

$org_names[0] - это коллекция.

Чтобы получить доступ к ним, вам нужно сделать что-то вроде:

foreach ($org_names[$org_names_counter] as $org) {
    echo $org->name;
    // ...
}

Но, глядя на код, кажется, что должно быть только быть 1 элемент в коллекции, как вы выбираете по идентификатору. В этом случае вы после единого результата. Чтобы получить один совпадающий результат, используйте:

$org_names[] = Organization::where('id', $datas->organization_id)->first();

Теперь $org_names[] это просто массив Organization с, и ваш существующий код представления будет работать.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...