2017-02-11 15 views
0

私はこのLaravelの新作で、Laravelのクイックスタートプロジェクトを試してみようとしていました。私はテンプレート内で設定された変数に慣れていません。私はを昇順または降順で並べ替えるために1つのボタン/リンクを作成しようとしていますすべての取得されたレコード。Laravelワンクリックで並べ替え

通常、私はswitch()を使用して基本的なPHPソートに問題はありませんが、私はLaravelを使用しているので、少し慣れていません。だからここにコードは次のとおりです。 -

routes.phpの

Route::group(['middleware' => ['web']], function() { 

Route::get('/sort/{id}', function ($id) { // get to the sorted page ("/sort") 
    switch ($id) { 
      case 'asc' : 
       return view('tasks', [ // get the tasks table from the database 
       'tasks' => Task::orderBy('name', 'asc')->get(), 
       'sort' => "desc" 
       // From the tasks table, get the listing from the table and arrange them descending by date of creation 
      ]); 
      case 'desc' : 
       return view('tasks', [ // get the tasks table from the database 
       'tasks' => Task::orderBy('name', 'asc')->get(), 
       'sort' => "asc" // From the tasks table, get the listing from the table and arrange them ascending by date of creation 
      ]); 
     } 
    }); 

tasks.blade.php

<div class="panel-body"> 
         <table class="table table-striped task-table"> 
          <thead> 
           <th><a href="/sort/{{$sort}}">Task</a></th> 
           <th>&nbsp;</th> 
          </thead> 
          <tbody> 
           @foreach ($tasks as $task) <!-- display the listings from the tasks table --> 
            <tr> 
             <td class="table-text"><div>{{ $task->name }}</div></td> 
             <td class="table-text"><div>{{ $task->description }}</div></td> 

             <!-- Task Delete Button --> 
             <td> 
              <form action="{{ url('task/'.$task->id) }}" method="POST"> <!-- form action select the id on the task table database($task->id) --> 
               {{ csrf_field() }} 
               {{ method_field('DELETE') }} <!-- delete the field --> 

               <button type="submit" class="btn btn-danger"> 
                <i class="fa fa-btn fa-trash"></i>Delete 
               </button> 
              </form> 
             </td> 
            </tr> 
           @endforeach 
          </tbody> 
         </table> 
        </div> 

私はインターネット上でのコードの一部を参照してくださいとのいくつかを作りますLaravelのHTML部分の中の変数には使用されていないので、自分自身です。私はそれが動作すると思ったが、コードを実行するとtasks.blade.phpundefined variable: sortがスローされます。通常、どの変数もバックエンドPHP内にありますが、これはまったく新しい環境です。だから、私はHTMLの変数はどのように動作するのだろうか?どのように並べ替えを動作させるには?

EDIT 1:エラーの

スクリーンショット: - あなたは、ソートタスクモデルは両方のケースで昇順ので

Error Error

答えて

0

私自身の質問の解決策を見つけました。 tasks.blade.php{{$sort}}を使用する代わりに、isset()関数を使用して変数が適切に設定されているかどうかを確認する必要があります。 Laravelので、そのための独自の機能を持って、私はちょうどそれらを使用する: -

{{{ isset($sort) ? $sort : 'asc' }}} 

これは、(asc)を昇順にデフォルトの初期$sort変数を設定することを意味します。

これはその答えです。ありがとう、私!

0

あなたのソートは、動作しません。あなたは、後者の場合には

Task::orderBy('name', 'desc')->get()

を使用する必要があります。変数については、スクリーンショットを提供する方がより明確になります。

+0

Ops ..私の悪い..まだ、私はtasks.blade.phpの未定義の変数に問題があります。私はエラーのスクリーンショットを提供しました。 – Kaydarin

関連する問題