Как реализовать простой поиск CRUD в Laravel? - PullRequest
0 голосов
/ 13 мая 2019

У меня есть таблица, которая содержит данные, и я хочу реализовать для нее функцию поиска. Например, я набрал бы запрос в строке поиска, и он просматривал бы похожие термины в столбцах таблицы, а затем отображал строки, содержащие совпадения.

Это ошибка, с которой я постоянно сталкиваюсь.

enter image description here

Я просто следовал этому учебнику и использовал мои переменные. Я не знаю, что я делаю не так. Я сделал все в соответствии с этим.

Вот мой код TicketController:

<?php

namespace App\Http\Controllers;

use App\Ticket;
use Illuminate\Http\Request;
use App\Http\Requests\TicketUpdateRequest;

class TicketController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {   
        $tickets= Ticket::latest()->paginate(10);
        return view('tickets.index', compact('tickets'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('tickets.create');
    }

    public function delete(Ticket $ticket)
    {
        return view('tickets.delete', ['tickets' => $tickets]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        Ticket::create([
        'summary'=>request('summary'),
        'description'=>request('description'),
        'status'=>request('status'),
        'updated_at'=>request('updated_at'),
        'name_client'=>request('name_client'),
        'contactnum'=>request('contactnum'),
        'location'=>request('location'),
        'rtype'=>request('rtype'),
        'personnel'=>request('personnel'),
        'priority'=>request('priority'),
        'notes'=>request('notes'),
        ]);

        return redirect()->route('tickets.index');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Ticket  $ticket
     * @return \Illuminate\Http\Response
     */
    public function show(Ticket $ticket)
    {
        return view('tickets.show', compact('ticket'));
    }


    public function search(Request $request)
    {
        $search = $request->get('search');
        $tickets = Ticket::latest('tickets')->orWhere('rtype', 'like', '%'.$search.'%')->paginate(10);
        return view('tickets.index',['tickets' => $tickets]);
    }



    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Ticket  $ticket
     * @return \Illuminate\Http\Response
     */
    public function edit(Ticket $ticket)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Ticket  $ticket
     * @return \Illuminate\Http\Response
     */
    public function update(TicketUpdateRequest $request, Ticket $ticket)
    {

        $ticket->summary = request('summary');
        $ticket->description = request('description');
        $ticket->status = request('status');
        $ticket->name_client= request('name_client');
        $ticket->contactnum= request('contactnum');
        $ticket->location= request('location');
        $ticket->rtype= request('rtype');
        $ticket->personnel= request('personnel');
        $ticket->priority= request('priority');
        $ticket->notes= request('notes');
        $ticket->save();



        return redirect()->route('tickets.index');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Ticket  $ticket
     * @return \Illuminate\Http\Response
     */
    public function destroy(Ticket $ticket)
    {
        $ticket->delete();
        return redirect()->route('tickets.index');
    }
}

и поисковая часть моей навигационной панели:

<form action="/search" method="get">
  <input class="form-control form-control-dark w-100" type="search" placeholder="Search" aria-label="Search"></form>

Вот также часть таблицы моей индексной страницы:

<table class="table table-striped table-sm">
  <thead>
    <tr>
      <th>Ticket</th>
      <th>Last Updated</th>
      <th>Subject</th>
      <th>Request Type</th>
      <th>Request Details</th>
      <th>Notes</th>
      <th>Priority</th>
      <th>Status</th>
      <th>Actions</th>
    </tr>
  </thead>
  <tbody>
    @foreach($tickets as $ticket)
    <tr>
      <td>{{$ticket->id}}</td>
      <td>{{$ticket->updated_at}}</td>
      <td>{{$ticket->summary}}</td>
      <td>{{$ticket->rtype}}</td>
      <td>{{str_limit($ticket->description, 40)}}</td>
      <td>{{str_limit($ticket->notes, 40)}}</td>
      <td>{{$ticket->priority}}</td>
      <td>{{$ticket->status}}</td>
      <td><a href="/tickets/{{$ticket->id}}" class="btn btn-primary">Update</a>
          <a href="/tickets/delete/{{$ticket->id}}" class="btn btn-danger">Delete</a>
      </td>
    </tr>
    @endforeach
  </tbody>
</table>

и, наконец, мои маршруты:

<?php


Route::get('/', function () {
    return view('welcome');
});

Route::get('/tickets', 'TicketController@index')->name('tickets.index')->middleware('auth');

Route::get('/tickets/create','TicketController@create')->name('tickets.create')->middleware('auth');

Route::post('/tickets/create','TicketController@store')->name('tickets.store')->middleware('auth');

Route::post('/tickets/{ticket}','TicketController@update')->name('tickets.update')->middleware('auth');

Route::get('/tickets/delete/{ticket}','TicketController@delete')->name('tickets.delete')->middleware('auth');

Route::post('/tickets/delete/{ticket}','TicketController@destroy')->name('tickets.destroy')->middleware('auth');


Route::get('/tickets/{ticket}','TicketController@show')->name('tickets.show')->middleware('auth');



Route::get('/', 'TicketController@index');
Route::get('/search','TicketController@search');
Route::resource('tickets','TicketController');

Route::get('/clientrequest','ClientRequestController@create')->name('clientrequest');

Route::post('/clientrequest','ClientRequestController@store')->name('clientrequest');


Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

Route::get('/logout', 'Auth\LoginController@logout');

Route::get('admin/routes', 'HomeController@admin')->middleware('admin');

РЕДАКТИРОВАТЬ: Это моя модель:

enter image description here

1 Ответ

0 голосов
/ 13 мая 2019

Последние и самые старые методы позволяют легко упорядочить результаты по умолчанию на дату или по столбцу.

Ticket::latest('tickets')->orWhere('rtype', 'like', '%'.$search.'%')->paginate(10);

В своем красноречивом запросе вы передаете столбец tickets для запроса orderBy (последний),Пока его нет в вашей таблице.Изменение порядка по дате created_at или любого другого столбца должно устранить ошибку.

Ticket::Where('rtype', 'like', '%'.$search.'%')->latest()->paginate(10);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...