Button for update function not working laravel 8 (CRUD) - laravel-8

I'm new to laravel 8. I try to make an update function controller when user already edit their data and store it in database. I try to click submit button and it's not working without any reason when i try to inspect at chrome. So i try another way which is comment the $request->validate and it's only change for name data while organisation_id leave blank and return to NULL. I wonder do we need to always validate the data in update function ?
Here is my Controller
public function edit($id)
{
$record = User::find($id);
$org = Organisation::all();
$t = Organisation::pluck("name");
return view ('user.edit',compact('record','org','t'));
}
public function edit_store(Request $request, $id)
{
$request->validate([
'name' => 'required',
'organisation_id' => 'required',
]
);
$record= User::find($id);
$record->name = $request->name;
$record->organisation_id = $request->organisation_id;
$record->save();
return redirect ('user')->with('success', 'Thank you');
}
Here is my edit blade
<div class="card">
<div class="card-body">
<form action="{{route('user_edit_store1', $record->id)}}" method="POST">
#csrf
<input type="hidden" name="id" value="{{ $record->id }}">
<div class="form-group row">
<label for="name"
class="col-md-4 col-form-label text-md-right">{{ __('Name') }}</label>
<div class="col-md-6">
<input id="name" type="text"
class="form-control #error('name') is-invalid #enderror" name="name"
value="{{ old('name') ? old('name') : $record->name }}"
</div>
</div>
<div class="form-group row">
<label for="organisation_id"
class="col-md-4 col-form-label text-md-right">{{ __('Organisation') }}</label>
<div class="col-md-6">
{!! Form::open(['route' => 'user_store']) !!}
{!! Form::select('id', $t, 'id', ['class' => 'form-control']) !!}
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary" >
{{ __('Save') }}
</button>
</div>
</div>
</form>
</div>
</div>
Routes
Route::get('user_edit/{id}',[UserController::class,'edit'])->name('user_edit');
Route::post('user_edit_store/{user}',[UserController::class,'edit_store'])->name('user_edit_store1');
Model user.php
protected $fillable = [
'name',
'organisation_id',
];

It appears that the <select> that you're creating with the Form::select form helper will have name of 'id' instead of 'organisation_id' which will result in a validation fail.

Related

How to display validation summary below the input controls?

I have the following form:
<form asp-controller="Manage" asp-action="RemoveDetails" method="post" class="form-horizontal">
#if (Model.RequirePassword)
{
<div id="password-container">
<div class="col-md-6">
<div class="form-group">
<label asp-for="Password"></label>
<input asp-for="Password" class="form-control" id="password" autocomplete="current-password" aria-required="true" />
<small>
<span asp-validation-for="Password" class="text-danger"></span>
</small>
</div>
</div>
</div>
}
<div class="col-6">
<hr class="mt-2 mb-3">
<button type="submit" class="btn btn-style-1 btn-danger">Confirm</button>
</div>
<div class="row">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
</div>
</form>
If I leave the password empty, a validation message (the model uses DataAnnonations) is displayed right below the control. This is fine.
If I enter the wrong password, the Post action validates it and adds an error to the ModelState. This error is displayed below the form.
Is it possible to display such model errors below the relevant controls?
Try this code in Controller: ModelState.AddModelError("Password", "validation summary error."); The error message won't display in <div asp-validation-summary="ModelOnly"></div>, but it can display error message in #Html.ValidationSummary(false, "", new { #class = "text-danger" }).
<form asp-controller="Home" asp-action="RemoveDetails" method="post" class="form-horizontal">
<div id="password-container">
<div class="col-md-6">
<div class="form-group">
<label asp-for="Password"></label>
<input asp-for="Password" class="form-control" id="password" autocomplete="current-password" aria-required="true" />
<small>
#*<span asp-validation-for="Password" class="text-danger"></span>*#
#Html.ValidationSummary(false, "", new { #class = "text-danger" })
</small>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label asp-for="Description"></label>
<input asp-for="Description" class="form-control" id="description" autocomplete="current-password" aria-required="true" />
<small>
<span asp-validation-for="Description" class="text-danger"></span>
</small>
</div>
</div>
</div>
<div class="col-6">
<hr class="mt-2 mb-3">
<button type="submit" class="btn btn-style-1 btn-danger">Confirm</button>
</div>
<div class="row">
<div asp-validation-summary="ModelOnly"></div>
</div>
</form>
[HttpPost]
public IActionResult RemoveDetails(RemoveDetail rdl)
{
if(ModelState.IsValid)
{
var pwd = rdl.Password;
//do something here and find the password is wrong
//code below won't display error message in <div asp-validation-summary="ModelOnly" class="text-danger">
//but can display error message in #Html.ValidationSummary(false, "", new { #class = "text-danger" })
ModelState.AddModelError("Password", "validation summary error.");
return View(rdl);
}
return View(rdl);
}

Preventing developer message to user frontend

I am developing a website with different pages, and among those pages,
I have a contact form that send message to the backend, the email id is unique, I need to display an error message to the front end that if a user enter the email that exist to then it has to display a message the email is taken. How can I go to achieve this. Here is my code
Controller
<?php
namespace App\Http\Controllers\Frontend;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Contact;
use Illuminate\Support\Carbon;
class FrontendPages extends Controller
{
public function About(){
return view('frontend.pages.about');
}//end method
public function Service(){
return view('frontend.pages.services');
}//end method
public function Blog(){
return view('frontend.pages.blog');
}//end method
public function Contact(){
return view('frontend.pages.contact');
}//end method
public function StoreMessage(Request $request){
Contact::insert([
'name' => $request->name,
'email' => $request->email,
'subject' => $request->subject,
'message' => $request->message,
'created_at' =>Carbon::now(),
]);
if ($request->email == 'email') {
return response()->json(['email exist']);
}
$notification = array(
'message' => 'Thank for being in touch we will get back to you soon',
'alert-type' => 'success'
);
return redirect()->back()->with($notification);
}
}
my form
#extends('frontend.main_master')
#section('main')
#php
$footersetup = App\Models\Footer::find(1)->first();
#endphp
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- ======= Breadcrumbs ======= -->
<section id="breadcrumbs" class="breadcrumbs">
<div class="container mt-3">
<div class="d-flex justify-content-between align-items-center">
<h2>Contact</h2>
<ol>
<li>Home</li>
<li>Contact</li>
</ol>
</div>
</div>
</section>
<!-- End Breadcrumbs -->
<!-- ======= Contact Section ======= -->
<section id="contact" class="contact">
<div class="container">
<div class="row mt-5">
<div class="col-lg-4">
<div class="info">
<h4>Location:</h4>
<div class="address">
<i class="bi bi-geo-alt"></i>
{!! $footersetup->address !!}<br /><br />
</div>
<div class="email">
<i class="bi bi-envelope"></i>
<h4>Email:</h4>
<p>
{{$footersetup->email}}<br />{{$footersetup->email1}}
</p>
</div>
<div class="phone">
<i class="bi bi-phone"></i>
<h4>Call:</h4>
<p>{{$footersetup->phone}}</p>
</div>
</div>
</div>
<div class="col-lg-8 mt-5 mt-lg-0">
<form
action="{{route('store.message')}}"
method="post"
role="form"
>
#csrf
<div class="row">
<div class="col-md-6 form-group">
<input
type="text"
name="name"
class="form-control"
id="name"
placeholder="Your Name"
required
/>
</div>
<div class="col-md-6 form-group mt-3 mt-md-0">
<input
type="email"
class="form-control"
name="email"
id="email"
placeholder="Your Email"
required
/>
</div>
</div>
<div class="form-group mt-3">
<input
type="text"
class="form-control"
name="subject"
id="subject"
placeholder="Subject"
required
/>
</div>
<div class="form-group mt-3">
<textarea
class="form-control"
name="message"
rows="5"
placeholder="Message"
required
></textarea>
</div>
<div class="my-3">
</div>
<div class="text-center">
<button type="submit" class="btn btn-success">Send Message</button>
</div>
</form>
</div>
</div>
</div>
</section>
<!-- End Contact Section -->
#endsection

after I fixed the error Route [Login] not defined, I can't log in even though I use the correct email and password

this is web.php
Route::get('/login', [LoginController::class, 'index'])->name('login')->middleware('guest');
Route::post('/login', [LoginController::class, 'authenticate']);
Route::post('/logout', [LoginController::class, 'logout']);
this is my LoginController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
public function index()
{
return view('login.index', [
'title' => 'Login'
]);
}
public function authenticate(Request $request)
{
$credentials = $request->validate([
'email' => 'required|email:dns',
'password' => 'required'
]);
if (Auth::attempt($credentials)) {
$request->session()->regenerate();
return redirect()->intended('/admin');
}
return back()->with('loginError', 'Login anda gagal !');
}
public function logout(Request $request)
{
Auth::logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect('/login');
}
}
this is my login view
<main class="form-signin">
#if (session()->has('Sukses'))
<div class="alert alert-success alert-dismissible fade show" role="alert">
{{ session('Sukses') }}
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
#endif
#if (session()->has('loginError'))
<div class="alert alert-danger alert-dismissible fade show" role="alert">
{{ session('loginError') }}
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
#endif
<form action="/login" method="post">
#csrf
<img class="mb-4" src="/img/discord.png" alt="" width="100" height="99">
<h1 class="h3 mb-3 fw-normal">Please Login</h1>
<div class="form-floating">
<input type="email" name="email" class="form-control #error('email') is-invalid #enderror" id="email" placeholder="name#example.com" autofocus required value="{{ old('email') }}">
<label for="email">Masukkan Email</label>
#error('email')
<div class="invalid-feedback">
{{ $message }}
</div>
#enderror
</div>
<div class="form-floating">
<input type="password" name="password" class="form-control" id="password" placeholder="Password" required>
<label for="password">Password</label>
</div>
<button class="w-100 btn btn-lg btn-primary" type="submit">Login</button>
</form>
<small class="d-block text-center mt-3">Not have any account? Register here</small>
<p class="mt-5 mb-3 text-muted">© 2022</p>
</main>

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'status_member' cannot be null

i have failed to save update data, the notification error message is SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'status_member' cannot be null (SQL: update daftar_pelanggans set alamat = gdsgzddgrrse, status_member = ?, daftar_pelanggans.updated_at = 2020-12-06 03:36:35 where id = 6)
this is the button edit
<button data-toggle="modal" data-target="#editModal-{{ $pelanggan->id }}" class="btn btn-sm btn-primary"><i class="fa fa-edit"></i></button>
this is the modal view
#foreach($daftar_pelanggan as $pelanggan)
<div class="modal fade" id="editModal-{{ $pelanggan->id }}" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title mb-0" id="editModalLabel">Update Data Pelanggan</h5>
</div>
<div class="modal-body">
<!-- Card body -->
<form role="form" action="{{ route('daftar_pelanggan.update', $pelanggan->id) }}" method="POST" id="editForm">
#csrf
#method('PUT')
<!-- Input groups with icon -->
<div class="form-group row">
<label for="updateNamaPelanggan" class="col-md-2 col-form-label form-control-label">Nama</label>
<div class="col-md-10">
<input type="hidden" name="id" value="{{ $pelanggan->id }}">
<input class="form-control" type="nama" value="{{ $pelanggan->nama_pelanggan }}" name="updateNamaPelanggan" required >
</div>
</div>
<div class="form-group row">
<label for="updateAlamat" class="col-md-2 col-form-label form-control-label">Alamat</label>
<div class="col-md-10">
<input class="form-control" type="alamat" value="{{ $pelanggan->alamat }}" name="updateAlamat" required>
</div>
</div>
<div class="form-group row">
<label for="updateNoTelp" class="col-md-2 col-form-label form-control-label">No.Telp</label>
<div class="col-md-10">
<input class="form-control" type="notelp" value="{{ $pelanggan->no_telp }}" name="updateNoTelp" required>
</div>
</div>
<div class="form-group row">
<div class="col-md-6">
<div class="form-group">
<label class="form-control-label" for="updatePoin">POIN</label>
<input type="text" class="form-control" value="{{ $pelanggan->poin }}" name="updatePoin">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="form-control-label" for="status_member">Kategori</label>
<!-- <h3>{{ $pelanggan->status_member }}</h3>-->
<select class="form-control" name="status_member" required="required">
<option value="silver" {{ $pelanggan->status_member === 'Silver' ? 'selected' : '' }} >Silver</option>
<option value="gold" {{ $pelanggan->status_member === 'Gold' ? 'selected' : '' }} >Gold</option>
<option value="diamond" {{ $pelanggan->status_member === 'Diamond' ? 'selected' : '' }} >Diamond</option>
</select>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="reset" class="btn btn-secondary" data-dismiss="modal">Reset</button>
<button type="submit" class="btn btn-primary">Update Data</button>
</div>
</form>
</div>
</div>
</div>
#endforeach
this is the route
Route::put('daftar_pelanggan/update/{id}', '\App\Http\Controllers\DaftarPelangganController#update')->name('daftar_pelanggan.update');
and this is the controller
public function update(Request $request, $id)
{
$update_pelanggan = DaftarPelanggan::find($id);
$update_pelanggan->nama_pelanggan = $request->updateNamaPelanggan;
$update_pelanggan->alamat = $request->updateAlamat;
$update_pelanggan->no_telp = $request->updateNoTelp;
$update_pelanggan->poin = $request->updatePoin;
$update_pelanggan->status_member = $request->updateKategori;
$update_pelanggan->save();
if($simpan){
Alert::success(' Berhasil Tambah data ', ' Silahkan dicek kembali');
}else{
Alert::error('data gagal disimpan ', ' Silahkan coba lagi');
}
return redirect()->back();}
what's wrong with this code ?
You have named the select control as status_member in the form while you are using $request->updateKategori in controller method/action while saving update data.
You can cross check by dd($request->all()) as first line of the update method and check which key value pairs are available as request data.
Change the update method like
public function update(Request $request, $id)
{
$update_pelanggan = DaftarPelanggan::findOrFail($id);
$update_pelanggan->nama_pelanggan = $request->updateNamaPelanggan;
$update_pelanggan->alamat = $request->updateAlamat;
$update_pelanggan->no_telp = $request->updateNoTelp;
$update_pelanggan->poin = $request->updatePoin;
//name of key $request->status_member must match name=status_member on select control in the form
$update_pelanggan->status_member = $request->status_member;
$update_pelanggan->save();
//------------- OR you can simply do ---------------------------//
//$update_pelanggam = DaftarPelanggan::findOrFail($id);
//$update_pelaggan->update($request->all();
//-------------------------------------------------------------//
if($simpan){
Alert::success(' Berhasil Tambah data ', ' Silahkan dicek kembali');
}else{
Alert::error('data gagal disimpan ', ' Silahkan coba lagi');
}
return redirect()->back();
}

How to clear form after submit in vuejs

I am trying to empty the form after it submits form but I am unable to do this. Here is the code
<form class="form-horizontal" #submit.prevent="addtodirectory" id="form-directory">
<div class="model-body">
<div class="card-body">
<div class="form-group row">
<label for="inputEmail3" class="col-sm-2 col-form-label">Name</label>
<div class="col-sm-10">
<input v-model="form.name" type="text" name="name"
class="form-control" :class="{ 'is-invalid': form.errors.has('name') }">
<has-error :form="form" field="name"></has-error>
</div>
</div>
<div class="form-group row">
<label for="inputEmail3" class="col-sm-2 col-form-label">Address</label>
<div class="col-sm-10">
<textarea v-model="form.address" type="text" name="address"
class="form-control" :class="{ 'is-invalid': form.errors.has('address') }"></textarea>
<has-error :form="form" field="address"></has-error>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Profession</label>
<div class="col-sm-10">
<input v-model="form.profession" type="text" name="profession"
class="form-control" :class="{ 'is-invalid': form.errors.has('profession') }">
<has-error :form="form" field="profession"></has-error>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Contact Number</label>
<div class="col-sm-10">
<input v-model="form.contact_number" type="text" name="contact_number"
class="form-control" :class="{ 'is-invalid': form.errors.has('contact_number') }">
<has-error :form="form" field="contact_number"></has-error>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">City</label>
<div class="col-sm-10">
<input v-model="form.city" type="text" name="city"
class="form-control" :class="{ 'is-invalid': form.errors.has('city') }">
<has-error :form="form" field="city"></has-error>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">State</label>
<div class="col-sm-10">
<select v-model="form.state" type="text" name="state"
class="form-control" :class="{ 'is-invalid': form.errors.has('state') }">
<has-error :form="form" field="state"></has-error>
<option value="Rajasthan">Rajasthan</option>
<option value="Gujrat">Gujrat</option>
</select>
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-success">Submit</button>
<button type="submit" class="btn btn-default float-right">Cancel</button>
</div>
<!-- /.card-footer -->
</div>
</form>
<script>
export default {
data() {
return {
news:{},
form: new Form({
name : '',
address:'',
profession:'',
city:'',
state:''
})
}
},
methods: { addtodirectory() {
this.$Progress.start();
this.form.post('api/addtodirectory');
Toast.fire({
type: 'success',
title: 'Directory Updated successfully'
})
$('#form-directory input[type="text"]').val('');
this.$Progress.finish();
}
}
I am using vform plugin to submit the form. Using Laravel as backend. The data is being submitted in database but I am not able to clear the form. please help in this regarding. Should I use jquery or javascript to clear the form? I tried different ways but I could not figure out the problem.
Simply empty your form object after form submit.
form: new Form({
name : '',
address:'',
profession:'',
city:'',
state:''
})
Well it was simple and I did following code for emptying the form.
addtodirectory(event) {
this.$Progress.start();
this.form.post('api/addtodirectory');
// document.getElementById("form-directory").reset();
console.log('durgesh');
// document.getElementsByName('name').value = '';
Toast.fire({
type: 'success',
title: 'Directory Updated successfully'
})
this.form.name = "";
this.form.profession ="";
this.form.address="";
this.form.city = "";
this.form.state = "";
this.$Progress.finish();
},
after submitting the form I did not used the form. so after doing this I emptied the form.
Or in a one-liner:
Object.keys(form).forEach(v => form[v] = "")
instead of:
this.form.name = "";
this.form.profession ="";
this.form.address="";
this.form.city = "";
this.form.state = "";