Переменная становится нулевой от контроллера к представлению без видимой причины - PullRequest
0 голосов
/ 29 октября 2018

Я застрял в следующей теме. Помощь будет очень ценится. Хотите сделать простой вызов для представления, но оно становится нулевым во время процесса. Первоначально я не делал фильтры, просто показывал все (примечания: все ()). Прямо сейчас я пытаюсь отфильтровать по дате, идентификатору или имени пользователя, это то, что я фиксирую на своих левых элементах управления до нажатия кнопки поиска (внизу). Но теперь с фильтрами (notas -sales-) он становится нулевым ... Я отправлю вам свой код, чтобы вы были добры и помогли мне определить причину. Я подозреваю о маршрутах (я впервые определяю их вручную).

enter image description here

Маршруты

    Route::get('notas/notasGet/', 'NotasController@notasGet')->name('notas.notasGet');
    Route::post('notas/notasPost/', 'NotasController@notasPost')->name('notas.notasPost');
    Route::get('notas/create/', 'NotasController@create')->name('notas.create');
    Route::get('notas/store/', 'NotasController@store')->name('notas.store');
    Route::put('notas/update/{id}', 'NotasController@update')->name('notas.update');
    Route::get('notas/{id}/edit', 'NotasController@edit')->name('notas.edit');
    Route::delete('notas/destroy/{id}', 'NotasController@destroy')->name('notas.destroy');
    Route::post('notas/cajaAbrir/', 'NotasController@cajaAbrir')->name('notas.cajaAbrir');
    Route::post('notas/cajaCortar/', 'NotasController@cajaCortar')->name('notas.cajaCortar');

Те, у кого проблема, - notasGet, notasPost, который я вызываю первым из индекса

Я звоню им из app.blade.php

<nav class="navbar navbar-expand-md navbar-light navbar-laravel">
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
                <ul class="navbar-nav ml-auto">
                        <li class="nav-item">
                            <a class="nav-link" href="/gymmgr/public/registroaccesos/destinationSearchGet/">Acceso</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="/gymmgr/public/notas/notasGet/">Venta</a>
                        </li>

На моем контроллере dd ($ notas); отлично работает

public function notasGet()
{
    $fechaInicio = null;
    $fechaFin = null;

    $headData = array('pageTitle' => 'Admin Home - View all destinations');

    $currentDate = Carbon::now()->format('Y-m-d');

    //$notas = Nota::whereRaw('dtmHoraCargo IS NULL')->get()->first();
    $notas = Nota::whereDate('dtmHoraCargo', '=', Carbon::today()->toDateString())->get();

    //dd($notas);

    $users = null;
    $users = User::all();

    $cajaAbierta = Caja::whereRaw('dtmCorte IS NULL')->get()->first();
    //dd($cajaAbierta);


    $data = array('notas'=>$notas,'fechaInicio'=>$fechaInicio,'fechaFin'=>$fechaFin, 'users'=>$users, 'caja'=>$cajaAbierta);
    return view('notas.index', $data);
}


public function notasPost(Request $request)
{

    $strSearch = $request->input('strSearch');
    $fechaInicio = $request->input('fechaInicio');
    $fechaFin = $request->input('fechaFin');
    $strPatron = $request->input('strPatron');


    $notas = null;


    switch ($strSearch) {
        case 0:
            $notas = Nota::whereDate('dtmHoraCargo', '=', Carbon::today()->toDateString())->get(); 
            break;
        case 1:
                $notas = Nota::whereRaw("dtmHoraCargo >= ? AND dtmHoraCargo <= ?",  array($fechaInicio." 00:00:00", $fechaFin." 23:59:59"))->get();
            break;
        case 2:
            $notas = Nota::find($strPatron); 
            break;
        case 3:
            $notas = Nota::whereDate('dtmHoraCargo', '=', Carbon::today()->toDateString())->get(); 
            break;
    }            



    $users = null;
    $users = User::all();

    $cajaAbierta = Caja::whereRaw('dtmCorte IS NULL')->get()->first();
    // dd($cajaAbierta);

    $data = array('notas'=>$notas,'fechaInicio'=>$fechaInicio,'fechaFin'=>$fechaFin, 'users'=>$users, 'caja'=>$cajaAbierta);


dd($notas); 



/*It echoes the right nota but suddenly and going to the view it's null and the view calling crashes.
    Nothing happens in between, so I don't know*/


    return view('notas.index', $data);
    //return view('registroaccesos.index', ['headData'=>$headData, 'usuarioSearch'=>$usuarioSearch]);
}

По индексу

  <table class="table">
    <thead class="thead-light">

      <tr>
        <th>Folio</th>
        <th>Fecha y hora</th>
        <th>Total</th>
        <th>Aplica a</th>
        <th>Saldo</th>
     </tr>
    </thead>
    <tbody>
      @foreach($notas as $nota)
      <tr>
        <td> <a href="/gymmgr/public/notas/{{ $nota->idNota }}/edit">{{ $nota->idNota }} </a>></td>
        <td> {{ $nota->dtmHoraCargo }} </td>
        <td> {{ $nota->dcmTotal }} </td>

        <td> {{ empty($nota->idAplicaA)? '' : $nota->aplicaa->strPaterno . ' ' . $nota->aplicaa->strMaterno . ' ' . $nota->aplicaa->strNombre }} </td>
        <td> {{ $nota->dcmSaldo }} </td>                
      </tr>

      @endforeach

    </tbody>
  </table>













    </main>
  </div>
</div>

это вызывает исключение (notas равно null, почему ????)

Попытка получить свойство 'idNota' необъекта (представление: C: \ xampp \ htdocs \ gymmgr \ resources \ views \ notas \ index.blade.php)

1 Ответ

0 голосов
/ 29 октября 2018

В вашем переключателе in case 2 вы получаете один объект, в других случаях вы получаете коллекцию. Таким образом, кажется, исключение случается в этом case 2.

case 2:
        $notas = Nota::find($strPatron); // Will return object, but not the collection.
        break;

Вы можете попробовать это:

case 2:
        $notas = collect(Nota::find($strPatron)); 
        break;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...