2017-02-11 118 views
0

我是这个Laravel的新手,并试图围绕Laravel的快速入门项目进行游戏。我不熟悉模板中的变量集。我试图创建一个按钮/链接按升序或降序排列所有检索到的记录。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.php中抛出undefined variable: sort。通常任何变量都在后端PHP中,但这对我来说是一个全新的环境。所以,我想知道HTML中的变量是如何工作的?如何使排序工作?

编辑1:

错误的截图: -

Error Error

回答

0

我发现了一个解决方案,为我自己的问题。在tasks.blade.php中我没有设置任何默认密钥,而是使用{{$sort}},我需要使用isset()函数来检查变量是否相应设置。由于Laravel有它自己的功能,我只是使用它们: -

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

这意味着它将设置默认的初始$sort可变进升(asc)。

这就是它的答案。谢谢,我!

0

您的排序不工作,在这两种情况下,因为你排序任务模式上升。你应该在第二种情况下使用

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

。如果你提供截图,关于变量会更清楚。

+0

Ops ..我的坏..但是,我有task.blade.php中未定义的变量错误的问题。我提供了错误的截图。 – Kaydarin