Я использую форму Laravel.
На данный момент я успешно создал CRUD для предложений в моем проекте, но меня беспокоит одна вещь:
Как мне установить кнопку «Удалить» в моем списке изображений вместо конкретной страницы редактирования?
Итак, вот мой код:
Включено:
use App\ImageTracking;
use App\Image;
use DB;
стол предлагает:
public function up()
{
Schema::create('offers', function (Blueprint $table) {
$table->increments('idOffers')->unsigned();
$table->integer('id_spons')->unsigned();
$table->foreign('id_spons')->references('id_sponsors')->on('sponsors')->onDelete('cascade')->onUpdate('cascade');
$table->string('Name_offre');
$table->string('title');
$table->string('subject');
$table->string('froms');
$table->string('TrackingURL');
$table->string('subId');
$table->string('unSub');
//->onDelete('cascade')->onUpdate('cascade');
$table->timestamps();
});
}
изображение таблицы:
public function up()
{
Schema::create('image', function (Blueprint $table) {
$table->increments('id_imageUnsb');
$table->integer('offers_id')->unsigned();
$table->foreign('offers_id')->references('idOffers')->on('offers')->onDelete('cascade')->onUpdate('cascade');
$table->string('imageUnsb');
$table->timestamps();
});
}
<tbody>
@foreach($offers->Images as $image)
<tr>
<td><img src = "{{ url('storage/photo/'.$image->imageUnsb) }}" width = "100px" height = "100px"></td>
<td>
<form action = " {{ url('/offers/'.$image->idOffers) }}" method = "post">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<button type = "submit" class = "deleteConfirmation btn btn-danger">Delete</button>
</form>
</td>
</tr>
@endforeach
</tbody>
и что мой контроллер:
public function destroyImageUnsb(Request $request, $id)
{
$image = Image::where('offers_id', $id)->first()->delete();
return redirect('editOffers');
}
Маршрут :
Route::delete('/offers/{idOffers}','OffersController@destroyImageUnsb');






Вы должны попробовать это:
Маршрут
Route::get('/offers/{idOffers}','OffersController@destroyImageUnsb')->name('offers');
Ваше мнение
@foreach($offers->Images as $image)
<tr>
<td><img src = "{{ url('storage/photo/'.$image->imageUnsb) }}" width = "100px" height = "100px"></td>
<td>
<a href = "{{ route('offers', [$image->offers_id]) }}" class = "btn btn-xs btn-primary">Delete</a>
</td>
</tr>
@endforeach
Ваша функция контроллера
use Redirect;
public function destroyImageUnsb($id)
{
$image = Image::where('offers_id', $id)->delete();
return Redirect::to('editOffers/'.$id);
}
Обновите свой маршрут editoffers, например:
Route::get('/editOffers/{id}','OffersController@edit');
Обновленный ответ
Ваше мнение
@foreach($offers->Images as $image)
<tr>
<td><img src = "{{ url('storage/photo/'.$image->imageUnsb) }}" width = "100px" height = "100px"></td>
<td>
<a href = "{{ route('offers', [$image->id_imageUnsb]) }}" class = "btn btn-xs btn-primary">Delete</a>
</td>
</tr>
@endforeach
Ваша функция контроллера
use Redirect;
public function destroyImageUnsb($id)
{
$offerId = Image::where('id_imageUnsb',$id)->first();
$offerId = $offerId->offers_id;
$image = Image::where('id_imageUnsb', $id)->delete();
return Redirect::to('editOffers/'.$offerId);
}
Комментарии не подлежат расширенному обсуждению; этот разговор был переехал в чат.
Попробуй это:
@foreach($users as $key => $user)
{!! Form::open(['route' => ['offers', $user->id],'method' => 'POST','style' => 'display:inline-block'])!!}
{{ Form::submit(($user->status == 1) ? 'Ban User' : 'Activate User', ["class"=> "btn btn-red confirm-action"]) }}
{!! Form::close() !!}
@endforeach
Если вы новичок в laravel или если ваш project is smallПРОПУСТИТЬ ОТВЕТ
Откройте свою модель, это может быть Offer, и вставьте в нее следующий код.
/**
* @function tableActionButtons
* @author Manojkiran <[email protected]>
* @param string $fullUrl
* @param integer $id
* @param string $titleValue
* @param array $buttonActions
* @usage Generates the buttons
* @version 1.0
**/
/*
NOTE:
if you want to show tooltip you need the JQUERY JS and tooltip Javascript
if you are not well in JavaScript Just Use My Function toolTipScript()
|--------------------------------------------------------------------------
| Generates the buttons
|--------------------------------------------------------------------------
|Generates the buttons while displaying the table data in laravel
|when the project is bigger and if you are laravel expert you this.
|But if you are the learner just go with basic
|
|Basically It Will generate the buttons for show edit delete record with the default
|Route::resource('foo',FooController);
|
|//requirements
|
|//bootstrap --version (4.1.3)
|// <link rel = "stylesheet"href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity = "" crossorigin = "">
|//fontawesome --version (5.6.0(all))
|//<link rel = "stylesheet" href = "https://use.fontawesome.com/releases/v5.6.0/css/all.css" integrity = "" crossorigin = "">
|
|if you want to show tooltip you nee the jquery and tooltip you need these js and toottipscript javascript or use my function toolTipScript
|
|//jquery
|// <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
|//popper js
|// <script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
|//bootstrap js
|// <script src = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
|
|usage
|option1:
|tableActionButtons(url()->full(),$item->id,$item->name);
|this will generate all the buttons
|
|option2:
|tableActionButtons(url()->full(),$item->id,$item->name,['edit',delete]);
|this will generate edit and delete the buttons
|
|option3:
|tableActionButtons(url()->full(),$item->id,$item->name,['edit',delete,delete],'group');
|this will generate all the buttons with button grouping
|
|option4:
|tableActionButtons(url()->full(),$item->id,$item->name,['show','edit','delete'],'dropdown');
|this will generate all the buttons with button dropdown
|
*/
public static function tableActionButtons($fullUrl,$id,$titleValue,$buttonActions = ['show', 'edit', 'delete'],$buttonOptions='')
{
//Value of the post Method
$postMethod = 'POST';
//if the application is laravel then csrf is used
$token = csrf_token();
//NON laravel application
// if (function_exists('csrf_token'))
// {
// $token = csrf_token();
// }elseif (!function_exists('csrf_token'))
// //else if the mcrypt id is used if the function exits
// {
// if (function_exists('mcrypt_create_iv'))
// {
// // if the mcrypt_create_iv id is used if the function exits the set the token
// $token = bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));
// }
// else{
// // elseopenssl_random_pseudo_bytes is used if the function exits the set the token
// $token = bin2hex(openssl_random_pseudo_bytes(32));
// }
// }
//action button Value
//(url()->full()) will pass the current browser url to the function[only aplicable in laravel]
$urlWithId =$fullUrl.'/'.$id;
//Charset UsedByFrom
$charset = 'UTF-8';
// Start Delete Button Arguments
//title for delete functions
$deleteFunctionTitle = 'Delete';
//class name for the deletebutton
$deleteButtonClass = 'btn-delete btn btn-xs btn-danger';
//Icon for the delete Button
$deleteButtonIcon = 'fa fa-trash';
//text for the delete button
$deleteButtonText = '';
//dialog Which needs to be displayes while deleting the record
$deleteConfirmationDialog = 'Are You Sure you wnat to delete ' . $titleValue;
$deleteButtonTooltopPostion = 'top';
// End Delete Button Arguments
// Start Edit Button Arguments
//title for Edit functions
$editFunctionTitle = 'Edit';
$editButtonClass = 'btn-delete btn btn-xs btn-primary';
//Icon for the Edit Button
$editButtonIcon = 'fa fa-edit';
//text for the Edit button
$editButtonText = '';
$editButtonTooltopPostion = 'top';
// End Edit Button Arguments
// Start Show Button Arguments
//title for Edit functions
$showFunctionTitle = 'Show';
$showButtonClass = 'btn-delete btn btn-xs btn-primary';
//Icon for the Show Button
$showButtonIcon = 'fa fa-eye';
//text for the Show button
$showButtonText = '';
$showButtonTooltopPostion = 'top';
// End Show Button Arguments
//Start Arguments for DropDown Buttons
$dropDownButtonName = 'Actions';
//End Arguments for DropDown Buttons
$showButton = '';
$showButton .='
<a href = "'.$fullUrl.'/'.$id.'"class = "'.$showButtonClass.'"data-toggle = "tooltip"data-placement = "'.$showButtonTooltopPostion.'"title = "'.$showFunctionTitle.'-'.$titleValue.'">
<i class = "'.$showButtonIcon.'"></i> '.$showButtonText.'
</a>
';
$editButton ='';
$editButton .='
<a href = "'.$urlWithId.'/edit'.'"class = "'.$editButtonClass.'"data-toggle = "tooltip"data-placement = "'.$editButtonTooltopPostion.'" title = "'.$editFunctionTitle.'-'.$titleValue.'">
<i class = "'.$editButtonIcon.'"></i> '.$editButtonText.'
</a>
';
$deleteButton='';
$deleteButton .='
<form id = "form-delete-row' . $id . '" method = "'.$postMethod.'" action = "'.$urlWithId.'" accept-charset = "'.$charset.'"style = "display: inline" onSubmit = "return confirm("'.$deleteConfirmationDialog.'")">
<input name = "_method" type = "hidden" value = "DELETE">
<input name = "_token" type = "hidden" value = "'.$token.'">
<input name = "_id" type = "hidden" value = "'.$id.'">
<button type = "submit"class = "'.$deleteButtonClass.'"data-toggle = "tooltip"data-placement = "'.$deleteButtonTooltopPostion.'" title = "'.$deleteFunctionTitle.'-'.$titleValue.'">
<i class = "'.$deleteButtonIcon.'"></i>'.$deleteButtonText.'
</button>
</form>
';
// $deleteButton = "<a href='index.php?page=de_activate_organization&action_id=$id' onClick=\"return confirm('Are you Sure to De Activate?')\"><span class='label label-success'>" ."Test" . "</span></a>";
$actionButtons = '';
foreach ($buttonActions as $buttonAction)
{
if ($buttonAction == 'show')
{
$actionButtons .= $showButton;
}
if ($buttonAction == 'edit')
{
$actionButtons .= $editButton;
}
if ($buttonAction == 'delete')
{
$actionButtons .= $deleteButton;
}
}
if (empty($buttonOptions))
{
return $actionButtons;
}
elseif (!empty($buttonOptions))
{
if ($buttonOptions == 'group')
{
$buttonGroup = '<div class = "btn-group" role = "group" aria-label = "">
'.$actionButtons.'
</div>';
return $buttonGroup;
}elseif ($buttonOptions == 'dropdown')
{
$dropDownButton =
'<div class = "dropdown">
<button class = "btn btn-secondary dropdown-toggle" type = "button" id = "dropdownMenuButton" data-toggle = "dropdown" aria-haspopup = "true" aria-expanded = "false">
'.$dropDownButtonName.'
</button>
<div class = "dropdown-menu" aria-labelledby = "dropdownMenuButton">
'.$actionButtons.'
</div>
</div>
';
return $dropDownButton;
}else
{
return 'only <code>group</code> and <code>dropdown</code> is Available ';
}
}
}
Хорошо, теперь он откроет ваш файл списка, это может быть index.blade.php
@foreach($offers->Images as $image)
<tr>
<td><img src = "{{ url('storage/photo/'.$image->imageUnsb) }}" width = "100px" height = "100px"></td>
<td>{!!App\Offer::tableActionButtons(url()->full(),$image->id,$image->id,['show','edit','delete'])!!}</td>
@endforeach
если вам нужен значок
dont forgot to add fontawesome css
вы не должны помещать форму внутри foreach