首页 > 解决方案 > 可以在同一视图中显示和编辑数据库记录吗?

问题描述

我有一个简单的管理视图,显示所有可能的任务。我想让管理员可以看到所有任务,并有可能在同一个视图中编辑每个任务。我有一个包含我所有任务数据的表格和每条记录的编辑按钮。

每个任务的编辑部分应显示在表格的右侧。

当单击该记录的编辑按钮时,我不确定如何将每个正确的任务项添加到视图的编辑部分

仅使用 laravel 和刀片可以做到这一点吗?

我的观点

@extends('layouts.app')
@section('content')

<div class="jumbotron text-center">
    <h2>ADMIN PANEL</h2>
</div>
<div class="container">
    <div class="row" >
        <div class="col-md-7">
            <table class="table">
            <thead>
                <tr>
                <th scope="col">#</th>
                <th scope="col">Name</th>
                <th scope="col">Price</th>
                <th scope="col">Actions</th>
                </tr>
            </thead>
            <tbody>
            @foreach($quests as $questIndex => $quest)
                <tr>
                <th scope="row">{{($questIndex + 1)}}</th>
                <td>{{$quest->name}}</td>
                <td>No price set</td>
                <td><a class="btn btn-outline-dark mr-2" data-toggle="collapse" href="#collapseExample" role="button" aria-expanded="false" aria-controls="collapseExample">Edit</a><a class="btn btn-outline-dark"> Delete</a></td>
                </tr>
            @endforeach  
            </tbody>
            </table>
            {{$quests->links() }}
        </div>
        // edit the quest here 
        <div class="col-md-4 collapse" id="collapseExample">
             <p> Edit the quest </p>
        </div>
    </div>
</div>
@endsection

我的控制器

class AdminController extends Controller
{
    public function index()
    {
        $quests = Quest::simplePaginate('20');
        return view('admin.index', compact('quests'));
    }
}

标签: phplaraveleloquent

解决方案


正如评论中所指出的,有几种方法可以做到这一点。

方法一:

在不使用 ajax 的情况下使用简单的路由(在我看来这将是一个不好的做法)

路线网

Route::post("editQuest", "MyControllerQuest@editQuest")->name("editQuest");

*.blade.php

然后,您将按照注释中的指示打开模态,然后有一个名为Make changes.

<form action="{{ route("editQuest") }}">
  ...
  <input type="hidden" name="quest_id" value=""> // You would need to update this value whenever a user clicks on the button to edit the record with the id of the quest
  <button type="submit">Make Changes</button>
</form>

然后在“MyControllerQuest”中进行更改并将用户重定向回上一页。

方法 2: 您可以进行 ajax 调用来进行更改。我不会写涵盖该主题的完整答案,因为这超出了问题的范围,但您可以点击此链接(Google 的第一个链接)Laravel 和 ajax

方法 2 的优点: 通过 ajax 进行更改,您不必再次加载整个页面,从而节省服务器必须获取您正在分页的 20 条记录

快乐编码!


推荐阅读