【问题标题】:Laravel - Arranging images in ascending and descending order with linksLaravel - 使用链接按升序和降序排列图像
【发布时间】:2018-05-19 15:27:29
【问题描述】:

我的控制器中有一个创建方法

public function create()
{
    $image = PropertyUser::where('user_id', '=', Auth::user()->id)->get();
    foreach($image as $property)
    {
        $id = $property->property_id;
    }
    $image_main = Image::where('property_id', $id)->get();
    return view('settings.photos', ['image_array' => $image_main]);
}

这是我的刀片视图

<form name="asc" action="{{route("settings.photos")}}" method="post" class="text-center">
        @csrf
        <input type="submit"  value="Ascending " class="settings-photos-header2 text-center"/>  |
    </form><form name="dec" action="{{route("settings.photos")}}" method="post"  class="text-center">
        @csrf
        <input type="submit"  value= " Descending" class="settings-photos-header2 text-center"/>
    </form>
    <h2 class="settings-photos-header2 text-center">Photo Gallery</h2>
    @foreach ($image_array as $images)
        <div class="image-warp"><img src="{{$images->filename}}"
                                     style="width:100px;height:100px;"><br/><span style="color: #1b1e21">{{$images->description}}</span>
        </form>
        </div>
        @endforeach

问题- 我怎样才能让 asc 按钮按升序和 des 降序对图像进行排序,有没有办法将它连接到我的控制器,或者有没有办法通过&lt;a href&gt; 链接按升序和降序对它们进行排序?

【问题讨论】:

标签: php laravel laravel-5


【解决方案1】:

首先,foreach 在每次迭代中都会覆盖$id,因此$id 的最终值是$property_id 来自$image 数组的最后一项的值。

您需要定义关系。

PropertyUser 类中添加:

public function images() {
  return $this->belongsTo(Image::class, 'property_id');
}

然后,在控制器中的 create 方法中:

public function create(Request $request) {    

  // use direction query parameter to define asc or desc sorting
  $order_direction = $request->query('direction');

  $property_user = PropertyUser::where('user_id', '=', Auth::user()->id)
                                 ->with(['images' => function($query) use ($order_direction) {
                                     $query->orderBy('id', $order_direction)                                     
                                 })->get();

  // here you can access an array with associated images:
  $images = $property_user->images;  

  return view('settings.photos', ['image_array' => $images]);
}

您指向已排序图像的链接应为:&lt;a href="/create.html?direction=asc"&gt;Sort asc&lt;/a&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-25
    • 1970-01-01
    • 1970-01-01
    • 2018-03-18
    • 1970-01-01
    • 1970-01-01
    • 2020-02-08
    • 2012-11-08
    相关资源
    最近更新 更多