尝试在控制器中传递带有两个参数的命名路由时,我收到 500 内部错误



因此,当我使用单个参数输入路由名称时,它可以完美运行,但是当我传递带有两个参数的命名路由时,我在控制台中收到一个 500 错误,如下所示:GET http://127.0.0.1:8000/admin/packages/package-programs/kathmandu/action?query= 500 (Internal Server Error).

<?php
namespace AppHttpControllersAdminVisible;
use IlluminateHttpRequest;
use IlluminateSupportStr;
use AppProgram;
use AppPackage;
use DB;
class PackageProgramController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index($packageSlug)
{
$showCounts = Program::count();
$packages = Package::firstOrFail();
return view('admin.pages.packageprogram',compact('showCounts','packageSlug','packages'));      
}
function action($packageSlug,Request $request)
{
if($request->ajax())
{
$output = '';
$query = $request->get('query');
if($query != '')
{
$data = DB::table('programs')
->where('id', 'like', '%'.$query.'%')
->orWhere('day', 'like', '%'.$query.'%')
->orWhere('Package_Type', 'like', '%'.$query.'%')
->orWhere('title', 'like', '%'.$query.'%')
->orderBy('id', 'desc')
->get();

}
else
{
$data = DB::table('programs')
->orderBy('id', 'desc')
->get();
}
$total_row = $data->count();
if($total_row > 0)
{
foreach($data as $row)
{
$packageProgram = ['packageProgram' => $row->id];
$route = route('PackageProgram.edit',['packageSlug' => $packageSlug, 'packageProgram' => $packageProgram]);
$output .= '

<tr>
<th scope="row"><input type="checkbox" name="ids[]" class="selectbox" value="'.$row->id.'" onchange="change()"></th>
<td onClick="location.href=''.$route.'' " style="cursor: pointer">'.$row->id.'</td>
<td onClick="location.href=''.$route.'' " style="cursor: pointer">'.$row->day.'</td>
<td onClick="location.href=''.$route.'' " style="cursor: pointer">'.$row->title.'</td>
<td onClick="location.href=''.$route.'' " style="cursor: pointer">'.$row->description.'</td>
</tr>
';
}
}
else
{
$output = '
<tr>
<td align="center" colspan="12">No Data Found</td>
</tr>
';
}
$data = array(
'table_data'  => $output,
'total_data'  => $total_row
);

echo json_encode($data);
}
}
public function create($packageSlug, Package $package) 
{
return view('admin.create.createPackageProgram',compact('packageSlug','package'));
}
public function store($packageSlug,Request $request) 
{
$packages = Package::where('slug', $packageSlug)->firstOrFail();
$data = request()->validate([
'day' => 'required',             
'title' => 'required',
'description' => 'required', 
]);
$packages->program()->create($data);
switch ($request->input('action')) {
case 'preview':
return redirect()->intended(route('PackageProgram',$packageSlug))->with('message', 'Package Program has been added.');
break;

default:
return redirect()->back()->with('message', 'Package Program has been added.');
break;
}
}
public function edit($packageSlug,Program $packageProgram,Package $package)  
{
return view('admin.edit.editPackageProgram',compact('packageSlug','packageProgram','package'));
}
public function update($packageSlug, Program $packageProgram)
{
$data = request()->validate([
'day' => 'required',
'title' => 'required',
'description' => 'required',
]);
$packageProgram->update($data);
return redirect()->intended(route('PackageProgram',$packageSlug))->with('message', 'Package Program has been updated.');
}
public function delete(Request $request) {
$data = request()->validate([
'deleteSelected' => 'required',
]);
$id = $request->get('ids');
$data = DB::delete('delete from programs where id in ('.implode(",",$id).')');
return redirect()->back()->with('message', 'Testimony has been deleted.');
}
}

我的刀片文件如下所示:

@extends('layouts.app')
@section('style')
<link href="{{ asset('css/Admin/sql-data-viewer.css') }}" rel="stylesheet">   
<style></style>
@endsection
@section('content')
<section class="data-viewer">
<div class="d-flex justify-content-between px-3">
<h3 class="text-white">Select {{$package->Package_Name}} {{$package->Package_Type}} Days to change</h3>
<a href="{{ route('PackageProgram.create',$packageSlug) }}"><button type="button" class="btn add-data text-white rounded-pill">Add Day &nbsp;<i class="fas fa-plus"></i></button></a>
</div>
<form>
@csrf
@method('DELETE')
@if(session()->has('message'))
<div class="alert alert-success">
{{ session()->get('message') }}
</div>
@endif 
<div class="d-flex justify-content-between selectDelete">
<div class="delete pl-3 mt-3 mb-3">
<label for="deleteSelected">Action:</label>
<select name="deleteSelected" id="deleteSelected" class="@error('deleteSelected') is-invalid @enderror" name="deleteSelected" >
<option disabled selected>---------</option>
<option>Delete Selected Package Program</option>
</select>
<button formaction="{{ route('PackageProgram.delete',$package) }}" formmethod="POST" type="submit" class="go" id="deleleGo" onclick="deleteBtn()">Go</button> 
&nbsp;&nbsp;<span id="selected">0</span> of {{$showCounts}} selected
@error('deleteSelected')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
<strong id="selectError">You must check at least one checkbox</strong>             
</div>
<div class="search pr-3 mt-3 mb-3">
<label for="search">Search:</label>
<input id="search" type="text" color="#000" class="rounded @error('search') is-invalid @enderror" name="search" value="{{ old('search') }}" autocomplete="search" placeholder="Search">
@error('search')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror 
</div>
</div>
<table class="table table-hover table-striped table-dark">
<thead>
<tr>
<th scope="col"><input type="checkbox" id="checkHead" class="selectall"></th>
<th scope="col">Id</th>
<th scope="col">Day</th>
<th scope="col">Title</th>
<th scope="col">Description</th>
</tr>
</thead>
<tbody></tbody>
</table>
</form>
</section>
@endsection
@section('script')
<script src="{{ asset('/js/sqlData.js') }}"></script>
<script>
$(document).ready(function(){

fetch_data();

function fetch_data(query = '')
{
$.ajax({
url:"{{ route('PackageProgram.action',$packageSlug) }}",
method:'GET',
data:{query:query},
dataType:'json',
success:function(data)
{
$('tbody').html(data.table_data);
}
})
}

$(document).on('keyup', '#search', function(){
var query = $(this).val();
fetch_data(query);
});
});
function checkboxError(){
var number = document.querySelectorAll('.selectbox:checked').length;
if(number  == 0) {
var a = document.getElementById("selectError").style.display = "block";
return false;
}
}
window.addEventListener('DOMContentLoaded', (event) => {
var deleteBtn = document.getElementById("deleleGo");
deleteBtn.onclick = checkboxError;
});
</script>
@endsection

所以我的路由文件看起来像这样:

Route::prefix('package-programs')->group(function() {
Route::get('/', 'AdminVisiblepackagePackageProgramController@index')->name('PackagePrograms');
Route::get('/action', 'AdminVisiblepackagePackageProgramController@action')->name('PackagePrograms.action');
Route::prefix('{packageSlug}')->group(function() {
Route::get('/', 'AdminVisiblePackageProgramController@index')->name('PackageProgram');
Route::get('/action', 'AdminVisiblePackageProgramController@action')->name('PackageProgram.action');
Route::get('/create', 'AdminVisiblePackageProgramController@create')->name('PackageProgram.create');
Route::post('/create', 'AdminVisiblePackageProgramController@store')->name('PackageProgram.store');
Route::delete('/delete','AdminVisiblePackageProgramController@delete')->name('PackageProgram.delete');
Route::get('/{packageProgram}/edit', 'AdminVisiblePackageProgramController@edit')->name('PackageProgram.edit');
Route::patch('/{packageProgram}', 'AdminVisiblePackageProgramController@update')->name('PackageProgram.update');
});
});

可能是我不知道如何使用两个参数传递命名路由,但在我的刀片文件中,我一直在这样做,并且在那里工作。是否必须在控制器中完成其他操作。

首先从刀片开始(请检查评论):

@extends('layout')
@section('content')
<div class="row">
<table class="table table-hover table-striped table-dark" id="slugTb">
<thead>
<tr>
<th scope="col"><input type="checkbox" id="checkHead" class="selectall"></th>
<th scope="col">Id</th>
<th scope="col">Day</th>
<th scope="col">Title</th>
<th scope="col">Description</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
@endsection
@section('scripts')
<script>
$(document).ready(function() {
var query = 'damnSon';
$.ajax({
url: "{{ route('test.action') }}",
method: 'GET',
data: {
'slug': '{{ $packageSlug }}',
'query': query
},
dataType: 'json',
})
.done(function(data) {
console.log(data) //use console.log to debug
$('#slugTb tbody').html(data.table_data); //set table id so that you don't miss the right one
})
.fail(function(err) {
console.log(err) //in case if error happens
})
.always(function() {
console.log( "complete" ); //result despite the response code
});
});
</script>
@endsection

您使用了不推荐使用的 jquery 方法,例如success检查
最好使用这三个:donefailalways

下一趟路线web.php

Route::get('action', ['as' => 'test.action', 'uses' => 'TestController@action']);

在您的情况下,最好使用Request参数袋,以便您可以根据需要添加尽可能多的参数。

下一个控制器

function action(Request $request)
{
$total_row = 1;
$packageSlug = $request->get('slug'); //names that you set in ajax data tag: {'slug': '{{ $packageSlug }}','query': query}
$query = $request->get('query');
$output = '<tr>
<td align="center" colspan="1">' . $packageSlug . '</td>
<td align="center" colspan="1">' . $query .'</td>
</tr>';
$data = array(
'table_data'  => $output,
'total_data'  => $total_row
);
return response()->json($data);
}

应从控制器返回一些内容,以便边栏选项卡可以显示数据和 json 对其进行编码,以便 js 可以解析它。这就是为什么return response()->json($data);

其他方式:

路线

Route::get('/action/{slug}/{query}',['as' => 'test.action', 'uses' => 'TestController@action']);

刀片脚本:

<script>
$(document).ready(function() {
var query = 'damnSon';
$.ajax({
url: 'action/{{ $packageSlug }}/' + query,
method: 'GET',
dataType: 'json',
})
.done(function(data) {
console.log(data) //use console.log to debug
$('#slugTb tbody').html(data.table_data); //set table id so that you don't miss the right one
})
.fail(function(err) {
console.log(err) //in case if error happens
})
.always(function() {
console.log( "complete" ); //result despite the response code
});
});
</script>

控制器

function action($slug, $query)
{
$total_row = 1;
$packageSlug = $slug;
$query = $query;
$output = '<tr>
<td align="center" colspan="1">' . $packageSlug . '</td>
<td align="center" colspan="1">' . $query .'</td>
</tr>';
$data = array(
'table_data'  => $output,
'total_data'  => $total_row
);
return response()->json($data);
}

不建议仅仅因为您在 ajax 请求中手动键入 route:url: 'action/{{ $packageSlug }}/' + query如果您的路由更改,您必须在 js 中更改它。

相关内容

  • 没有找到相关文章

最新更新