首页 > 解决方案 > 查看未从控制器 Laravel 8 接收变量

问题描述

正如标题所说,使用其他控制器和视图我可以发送数据,但我不能使用控制器和视图,我将在下面发布。

控制器代码(它是一个资源控制器,但我使用的是自定义函数)

<?php

namespace App\Http\Controllers;
use App\Models\Persona;
use Illuminate\Http\Request;

class PersonaController extends Controller
{

public function mostrarMedicos(){
    $medicos = Persona::where('idTipoPersona', 4)->get();
    return view('gestionMedicos',compact($medicos));

} }

查看代码

@extends('layouts.app')

@section('content')

<h1>Gestión Médicos</h1>
<div class="container">
    <table class="table table-bordered table-hover">
        <tr class="info">
            <th>Nombre</th>
            <th>Apellido</th>
            <th>Cedula</th>
            <th>Email</th>
            <th>Teléfono</th>
            <th>Dirección</th>
            <th>Ciudad Residencia</th>
            <th>Fecha de Nacimiento</th>
            <th>Género</th>
        </tr>
        @foreach ($medicos as $medico)
            <tr>
                <td>{{$medico->nombre}}</td>
                <td>{{$medico->apellido}}</td>
                <td>{{$medico->cedula}}</td>
                <td>{{$medico->email}}</td>
                <td>{{$medico->telefono}}</td>
                <td>{{$medico->direccion}}</td>
                <td>{{$medico->ciudadResi}}</td>
                <td>{{$medico->fechaNacimiento}}</td>
                <td>{{$medico->genero}}</td>
            </tr>
        @endforeach
    </table>

路线

Route::get('/gestionarMedicos', [PersonaController::class,'mostrarMedicos'])->name('personaMostrarMedicos');

这是我得到的错误

Undefined variable $medicos (View: D:\xampp\htdocs\SistemaHNF\resources\views\gestionMedicos.blade.php)

我是 Laravel 的新手,我不明白为什么我会收到这个错误,如果据我所知,控制器应该返回带有$medicos应该包含数据的变量的视图。

(英语不是我的主要语言,因此对任何错误感到抱歉,如果需要,我可以发布任何额外的代码或更详细地解释一些东西)。

标签: phplaravellaravel-8

解决方案


您已经返回查询生成器并且忘记调用get()first()并且还错了compact

public function mostrarMedicos(){
        $medicos = Persona::where('idTipoPersona', 4)->get();
        return view('gestionMedicos',compact('medicos'));
}

推荐阅读