I am confused about wanting to delete a data according to id
the problem is that when you delete it, it's not the one from the cursor you're aiming at, it deletes it from the first id instead
web.php
Route::resource('dashboard/posts', DashboardPostController::class)->names([
'index' => 'post-dashboard',
'show' => 'post-show',
'create' => 'post-create',
'edit' => 'post-edit',
'destroy' => 'post-delete',
'update' => 'post-edit'
]);
postcontroller.php
public function destroy(Post $post)
{
if ($post->image) {
Storage::delete($post->image);
}
Post::destroy($post->id);
$notif = [
'message' => 'Data has been Deleted',
'alert-type' => 'success'
];
return redirect()->route('post-dashboard')->with($notif);
}
post.blade.php /view
<form action="{{ route('post-delete', $post->slug) }}" method="POST" class="d-inline" id="deleteForm">
#csrf
#method('DELETE')
<button type="button" class="badge bg-danger border-0">
<i class="material-icons opacity-10" onclick=" confirmDelete()">cancel</i>
</button>
</form>
post Models
public function getRouteKeyName()
{
return 'slug';
}
public function sluggable(): array
{
return [
'slug' => [
'source' => 'title'
]
];
}
anyone can help me please check my code
Need to Change in Destroy method inside the controller.
Use Model Eloquent delete facade for deleting the current record.
Change the destroy function with this code:
public function destroy(Post $post)
{
if ($post->image) {
Storage::delete($post->image);
}
$post->delete();
$notif = [
'message' => 'Data has been Deleted',
'alert-type' => 'success'
];
return redirect()->route('post-dashboard')->with($notif);
}
Related
I'm trying to add a notification after the users submit a form
here's my controller;
public function store(Request $request)
{
$data = request()->validate([
'package' => 'required',
'amt_paid' => 'required',
'bankname' => 'required',
]);
auth()->user()->funds()->create($data);
$user_id = auth()->user()->id;
return redirect('funds.create')->with('status', 'successfully inserted');
}
You can show your flash message in your view like this:
#if(session()->has('status'))
<div class="alert alert-success">
{{ session()->get('status') }}
</div>
#endif
Since you are already returning the status with a message from your controller
return redirect('funds.create')->with('status', 'successfully inserted');
You can also set the session variable this way
public function store(Request $request)
{
$data = request()->validate([
'package' => 'required',
'amt_paid' => 'required',
'bankname' => 'required',
]);
auth()->user()->funds()->create($data);
$user_id = auth()->user()->id;
// Persistent session
// session(['status'=>'successfully inserted']);
return redirect('funds.create')->with(['status'=>'successfully inserted']);
}
and get the session variable in Laravel Blade this way
#if(session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
#endif
I already asked this question but there are a few things different this time. Last time the problem was fixed pretty well so now i just need a hand to tell me how to change the code so it works properly.
The thing i have changed is that i have implemented a way to successfully lend more then one book at once. So now i have an array which works perfectly.
So this is my View imagine this code 3 times one for every book you want to lend:
<div class="form-group row">
<label for="serialnumber" class="col-md-4 col-form-label text-md-right">{{ __('Gerät 1 (serialnumber) :') }}</label>
<div class="col-md-6">
<input id="serialnumber" type="text" class="form-control{{ $errors->has('serialnumber') ? ' is-invalid' : '' }}" name="serialnumber[]" value="{{ old('serialnumber') }}" required #if (Session::has('autofocus')) autofocus #endif>
#if ($errors->any())
<div class="alert alert-danger">The book with this serialnumber is already lend by antoher person
<ul>
</ul>
</div>
#endif
</div>
</div>
This is my Controller Code now:
public function store(BookRequest $request)
{
//if( !Book::find($request->get('serialnumber'))->exists() ) {
$this->middleware('guest');
request()->validate([
'serialnumber' => 'required',
'ma_id' => 'required'
]);
$requestData = $request->all();
$data = [
[
'serialnumber' => $requestData['serialnumber'][0],
'comment' => $requestData['comment'],
'ma_id' => $requestData['ma_id'],
],
[
'serialnumber' => $requestData['serialnumber'][1],
'comment' => $requestData['comment'],
'ma_id' => $requestData['ma_id'],
],
[
'serialnumber' => $requestData['serialnumber'][2],
'comment' => $requestData['comment'],
'ma_id' => $requestData['ma_id'],
]
];
Book::insert($data);
return redirect()->route('borrow.index')
->with('success','Successfully lend the book');
}
And the last is my Request.php page:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class BookRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'serialnumber[0]' => 'required|unique:borrowed,serialnumber,null',
'serialnumber[1]' => 'required|unique:borrowed,serialnumber,null',
'serialnumber[2]' => 'required|unique:borrowed,serialnumber,null',
'ma_id' => 'required',
];
}
public function messages()
{
return [
'serialnumber' => 'Seems like you have added the same book more than once!',
];
}
}
And this is my error message which i got after i tried to lend a book which is already lend by another person. Before i implemented the array thing this code worked perfect. Another question that i have is how could i implement a way which shows an error message which says "Sorry but this book is currently not in our database please press the info button and get some administraive help" so that basically an error message appears when the book is not in our database we have a lot of books so it is possible that we forget to scan one. Every help is much appreciated!!
EDIT:
Forgot the error message
htmlspecialchars() expects parameter 1 to be string, array given
Change your view:
#if(!empty(old('serialnumber')))
#foreach(old('serialnumber') as $i=>$value)
<input id="serialnumber" type="text" class="form-control{{ $errors->has('serialnumber') ? ' is-invalid' : '' }}" name="serialnumber[]" value="{{ old('serialnumber.'.$i) }}" required #if (Session::has('autofocus')) autofocus #endif>
#endforeach
#endif
where $i is your array index
aslo you can modify your rules and message like:
public function rules(){
return [
'serialnumber.0' => 'required|unique:borrowed,serialnumber,null',
'serialnumber.1' => 'required|unique:borrowed,serialnumber,null',
'serialnumber.2' => 'required|unique:borrowed,serialnumber,null',
'ma_id' => 'required',
];
}
or
public function rules(){
return [
'serialnumber.*' => 'required|unique:borrowed,serialnumber,null',
'ma_id' => 'required',
];
}
and
public function messages()
{
return [
'serialnumber.*' => 'Seems like you have added the same book more than once!',
];
}
I'm trying to add my own action button in Yii2-Kartik Gridview.
This is my custom button:
This is my code in index.php
[
'class' => 'yii\grid\ActionColumn',
'template' => '{edit}',
'buttons' => [
'edit' => function ($url, $model) {
return Html::a('<button type="button" class="btn btn-edit-npwp"><i class="glyphicon glyphicon-plus-sign"></i></button>', $url, [
'title' => Yii::t('app', 'Edit'),
'data-toggle' => "modal",
'data-target' => "#myModal",
'data-method' => 'post',
]);
},
],
'urlCreator' => function ($action, $model, $key, $index) {
if ($action === 'edit') {
$url = Url::toRoute(['vatout-faktur-out/add-data', 'id' => $model->fakturId], ['data-method' => 'post',]);
return $url;
}
}
],
and this is my action in controller.php
public function actionAddData($id) {
$model = new VatoutFakturOut();
return $this->render('addData', [
'model' => $model,
]);
}
I want to process the data from the row that I've clicked the button.
But, this return error
Missing required parameters: id
Why does this happen? And how to fix this?
Thanks
In urlCreator you used if statement to check, if action is edit, and if it is, you add param id to your button url. Otherwise it doesnt have one, so there's two solutions:
Remove if statement from:
'urlCreator' => function ($action, $model, $key, $index) {
$url = Url::toRoute(['vatout-faktur-out/add-data', 'id' => $model->fakturId]);
return $url;
}
Or remove$id from your actionAddData() - because youre not using it at all:
public function actionAddData() {
$model = new VatoutFakturOut();
return $this->render('addData', [
'model' => $model,
]);
}
I have a model with a custom validation method. For testing it always returns an error message.
public function rules()
{
return [
...
['staff_ids', 'each', 'rule' => ['string']],
[['staff_ids'], 'validateStaffIds'],
...
];
}
public function validateStaffIds($attribute, $params, $validator) {
$this->addError($attribute, 'There is an error in the staff ids');
}
In the view.php is the modal element
<p>
<?= Html::button('Add Ensemble Staff',
['value' => Url::to(['ensemble/add', 'id' => $model->id]),
'title' => 'Adding New Ensemble Staff',
'class' => 'showModalButton btn btn-primary']);
?>
</p>
<?php
Modal::begin([
'closeButton' => [
'label' => 'x',
],
'headerOptions' => ['id' => 'modalHeader'],
'id' => 'modal',
'size' => 'modal-lg',
]);
echo "<div id='modalContent'></div>";
Modal::end();
?>
The js code which fires everything up...
$(function(){
$(document).on('click', '.showModalButton', function(){
if ($('#modal').data('bs.modal').isShown) {
$('#modal').find('#modalContent')
.load($(this).attr('value'));
} else {
//if modal isn't open; open it and load content
$('#modal').modal('show')
.find('#modalContent')
.load($(this).attr('value'));
}
//dynamiclly set the header for the modal
...
});
});
And the ensemble controller which handles the add action
public function actionAdd($id)
{
$model = $this->findModel($id);
// in the post ( 'ensembleStaff_ids' => [0 => '2']); where the id actually is staff_id
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $id]);
} else {
return $this->renderAjax('add', [
'model' => $model,
]);
}
}
And the form which is injected by the js into the model (Url::to(['ensemble/add', 'id' => $model->id]), )
<?php $form = ActiveForm::begin(['id' => 'add-theater-stuff-form']); ?>
<?= $form->field($model, 'staff_ids')->widget(Select2::className(), [
'model' => $model,
'data' => ArrayHelper::map(app\models\TheaterStaff::find()->where(['theater_id' => $model->theater_id])->all(), 'staff_id', 'staff.fullname'),
'options' => [
'multiple' => true,
'prompt' => 'Ensemble Staff',
],
'pluginOptions' => [
'tags' => true
]
]); ?>
<div class="form-group">
<?= Html::submitButton('Add', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
Clicking on the Add Ensemble Staff Button works fine and brings up the modal window. The form itself works fine so far; also the default validation works. Even the custom validation is called, but return $this->renderAjax(...) isn't load in the modal window anymore; it is separately.
A picture showing the modal loaded, the result after submit and a modal with default validation.
I found a similar problem here. But adding an id to the form, doesn't solve the problem. So how to get the default validation showing up properly in the modal window? Does anyone have a clue?
Solution
Thanks for the response. For me the solution was:
Enable ajax in the form
<?php $form = ActiveForm::begin(['id' => 'add-ensemble-stuff-form', 'enableAjaxValidation' => true]); ?>
And to add the following logic in the controller
public function actionAdd($id)
{
$model = $this->findModel($id);
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
} else {
// in the post ( 'ensembleStaff_ids' => [0 => '2']); where the id actually is staff_id
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $id]);
} else {
return $this->renderAjax('add', [
'model' => $model,
]);
}
}
}
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}else{/* your code */}
add this in controller use yii\web\Response
I have normal login form which work great. Now I'm trying to make second simple step when user enter his password and user name and if they are correct to redirect him to new page where he must enter pass phrase in order to continue.
I'm not sure if this is correct what I have make so far. This is my route:
Route::get ('/users/login', ['uses' => 'UsersController#login', 'before' => 'guest']);
Route::post('/users/login', ['uses' => 'UsersController#loginSubmit', 'before' => 'guest']);
// new
Route::get('/users/auth', ['uses' => 'UsersController#loginAuth', 'before' => 'guest']);
Route::post('/users/auth', ['uses' => 'UsersController#loginSubmitAuth', 'before' => 'auth|csrf']);
This is my auth.blade.php
{{ Form::open(['class' => 'form-horizontal']) }}
<div class="form-group"> {{ Form::textarea('key', ['class' => 'form-control', 'id' => 'key', 'autocomplete' => 'off']) }} </div><br/>
<hr />
<div class="row">
<button type="submit" class="btn btn-primary col-xs-4 col-xs-offset-4">Login</button>
</div>
<hr />
{{ Form::close() }}
This is my controller
public function login() {
return View::make('site.users.login');
}
public function loginSubmit() {
$validatorRules = array(
'captcha' => 'required|captcha',
'username' => 'required|alpha_dash',
'password' => 'required|min:6'
);
Input::merge(array_map('trim', Input::all()));
$validator = Validator::make(Input::all(), $validatorRules);
if ($validator->fails()) {
return Redirect::to('/users/login')->withErrors($validator->errors())->withInput(Input::except(['captcha']));
}
$user = User::where('username', Input::get('username'))->first();
if (!$user) {
$validator->messages()->add('username', 'Invalid login or password.');
return Redirect::to('/users/login')->withErrors($validator->errors())->withInput(Input::except(['captcha']));
}
if (!Hash::check(Input::get('password'), $user->password)) {
$validator->messages()->add('username', 'Invalid login or password.');
return Redirect::to('/users/login')->withErrors($validator->errors())->withInput(Input::except(['captcha']));
}
//$user->last_login = \Carbon\Carbon::now();
//$user->save();
//Session::put('user', ['user_id' => $user->user_id]);
return Redirect::to('/users/auth');
}
public function loginAuth() {
return View::make('site.users.auth');
}
public function loginSubmitAuth() {
$validatorRules = array(
'key' => 'required',
'captcha' => 'required|captcha'
);
Input::merge(array_map('trim', Input::all()));
$validator = Validator::make(Input::all(), $validatorRules);
if ($validator->fails()) {
return Redirect::to('/users/auth')->withErrors($validator->errors())->withInput(Input::except(['captcha']));
}
$user = User::where('key', Input::get('key'))->first();
if (!$user) {
$validator->messages()->add('key', 'Invalid Key.');
return Redirect::to('/users/auth')->withErrors($validator->errors())->withInput(Input::except(['captcha']));
}
$user->last_login = \Carbon\Carbon::now();
$user->save();
Session::put('user', ['user_id' => $user->user_id]);
return Redirect::to('/');
}
Current error is 'Array to string conversion'
Any help is appreciated. Thank's
The issue of second parameter in Form::textarea you need to pass null to make it empty in second parameter and array in third parameter like,
<div class="form-group">
{{ Form::textarea('key',null, ['class' => 'form-control', 'id' => 'key', 'autocomplete' => 'off']) }}
</div><br/>
You can refer to Creating a Textarea Input Field
Can you try if this fixes your problem:
{{ Form::textarea('key', null, ['class' => 'form-control', 'id' => 'key', 'autocomplete' => 'off']) }}
It's this way because the value argument comes second and it is mandatory in difference with the third one which is optional