I have a form that has username, job, date of birth and city inputs. I am trying to update them through my form. When I click submit button my form submits but data remains unchanged. I successfully read them from database but when I try and update nothing happens. Any help is appreciated. Here is my code.
UserController.php
public function showProfile($username, Request $request)
{
$profileId = User::getIdFromUsername($username);
$userForShowProfile = User::with('userProfile')->where('id', $profileId)->first();
return view('profile.show', compact('userForShowProfile'));
}
public function updatePersonalData(UpdatePersonalDataRequest $request)
{
$user = Auth::user();
$request->validated();
$user->where('id', $user->id)->update(
[
'username' => $request->username,
'job' => $request->job,
'date_of_birth' => $request->date_of_birth,
'updated_at' => Carbon::now()
]
);
$city = City::where('name', $request['city'])->first();
if ($city != null && $city->count() > 0) {
$request->user()->city()->associate($city->id);
}
$request->user()->save();
return response()->json(null, 204);
}
web.php
Route::get('profile/{profile}', 'UserController#showProfile')->name('profile.show');
Route::patch('profile/personal', 'UserController#updatePersonalData')->name('profile.update.personal.data');
show.blade.php
<section data-edit="generalInfo" class="editGeneralInfo">
<form action="{{ route('profile.update.personal.data') }}" method="POST" class="flex">
#method('PATCH')
#csrf
<div class="form-group">
<label for="" class="textBold">Name</label>
<input type="text" name="username" value="{{ $userForShowProfile->username }}">
</div>
<div class="form-group">
<label for="" class="textBold">Ort</label>
<input type="text" name="job" value="{{ $userForShowProfile->job }}">
</div>
<div class="form-group">
<label for="" class="textBold">Beruf</label>
<input type="text" name="city" value="{{ $userForShowProfile->city->name }}">
</div>
<div class="form-group mb-0">
<label for="" class="textBold">Geburtsdatum</label>
<input type="text" placeholder="dd/mm/yyyy" name="date_of_birth" value="{{ $userForShowProfile->date_of_birth }}">
<p class="infoText mt-2">Dein Geburtsdatum wird nicht öffentlich angezeigt.</p>
<p class="infoText">Wir ermitteln damit nur dein Alter</p>
</div>
<div class="form-group">
<label for="" class="textBold">Button</label>
<input type="submit" class="form-control" name="submit" value="BUTTON">
</div>
</form>
</section>
rules
public function rules()
{
return [
'username' => ['string', 'max:255', 'unique:users,username'],
'job' => ['string', 'max:255'],
'date_of_birth' => ['date', 'date_format:d.m.Y'],
'city' => ['string', 'max:255', 'exists:cities,name']
];
}
I have a same problem in my code the error is:
I save like this : $user->save();
While i change the data using: $user and $user->profile
So i added in my code another line: $user->profile->save()
It work now
Related
I tried to store data but data not store to database, the field in database and form input already match but still can't store data, and there is no actual message error. please help.
this is my controller:
public function store(Request $request)
{
$validatedData = $request->validate([
'kabupaten' => ['required'],
'provinsi' => ['required'],
'unit' => ['required'],
'satuan_kerja' => ['required'],
'nama_area' => ['required'],
'kode_area' => ['required']
]);
Area::create($validatedData);
return redirect('/dashboard/areas')->with('success','Area baru telah ditambahkan!');
}
this is the form input:
<form action="/dashboard/areas" method="POST">
#csrf
<div class="mb-3">
<label for="provinsi" class="form-label">Provinsi</label>
<input type="text" class="form-control" id="provinsi" name="provinsi" value="Jawa Tengah">
</div>
<div class="mb-3">
<label for="kabupaten" class="form-label">Kabupaten</label>
<input type="text" class="form-control" id="kabupaten" name="kabupaten" value="Brebes">
</div>
<div class="mb-3">
<label for="unit" class="form-label">Unit</label>
<input type="text" class="form-control" id="unit" name="unit" value="Pemerintah Kabupaten Brebes">
</div>
<div class="mb-3">
<label for="satuan_kerja" class="form-label">Satuan Kerja</label>
<input type="text" class="form-control" id="satuan_kerja" name="satuan_kerja" value="Pemerintah Desa Dumeling">
</div>
<div class="mb-3">
<label for="nama_area" class="form-label">Nama Area</label>
<input type="text" class="form-control" id="nama_area" name="nama_area">
</div>
<div class="mb-3">
<label for="kode_lokasi" class="form-label">Kode Lokasi</label>
<input type="text" class="form-control" id="kode_lokasi" name="kode_lokasi">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
And this is my area model:
class Area extends Model
{
use HasFactory;
protected $primaryKey = 'id_area';
protected $guarded = [
'id_area'
];
public function aset(){
return $this->hasMany(Aset::class, 'id_area');
}
}
Thank you if there anyone can help me with this problem, I really appreciate it.
So most likely your validation is failing, what you need to do is to display the results of the failed validation error messages, and you can do so in your blade file:
#if ($errors->any())
#foreach ($errors->all() as $error)
<div>{{$error}}</div>
#endforeach
#endif
You may read more on how to display the errors here: https://laravel.com/docs/9.x/validation#quick-displaying-the-validation-errors
You can as well display it per input field or change the class of the input method, etc.. check the #error directive from here: https://laravel.com/docs/9.x/validation#the-at-error-directive
This question already has answers here:
How to pass data to view in Laravel?
(15 answers)
Passing data from controller to view in Laravel
(10 answers)
Laravel how to pass data from controller to blade [duplicate]
(6 answers)
Closed 1 year ago.
I want the user to view another page when the user clicks the button. inside the new page, some information is already fetched from the database. however, I declare everything but it still saying undefined variable.
form.blade.php
#foreach ($jobs as $job)
<form action="{{route('job-apply', $job->$id)}}" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group form-group-material a-form-group">
<label class="label">Full name</label>
<input type="text" class="form-control" name="fullname" required />
</div>
<div class="form-group form-group-material a-form-group">
<label class="label">Email</label>
<input type="email" class="form-control" name="email" required />
</div>
<div class="form-group form-group-material a-form-group">
<label class="label">Phone Number</label>
<input type="tel" class="form-control" name="contact" required />
</div>
<div class="form-group form-group-material a-form-group">
<label class="label">Address</label>
<textarea class="form-control" name="address" cols="30" rows="3"></textarea>
</div>
<div class="form-group form-group-material a-form-group">
<label class="label">Category</label>
<input type=text class="form-control" name="category" disabled value="{{ $job->category }}" required />
</div>
<div class="form-group form-group-material a-form-group">
<label class="label">Position</label>
<input type="text" class="form-control" name="position" disabled value="{{ $job->position}}" required />
</div>
<div class="form-group control-file a-file">
<input type="file" name="attachment" accept=".doc,.pdf" multiple />
<div class="file-path-wrapper">
<i class="lni lni-paperclip text-primary"></i>
<input class="file-path form-control" placeholder="Add Attachment(.doc;.pdf)" />
</div>
</div>
<button class="btn btn-success" type="submit">Send</button>
</form>
#endforeach
I have an error inside my form.blade
formcontroller
$jobs = Job::get();
$jobs=Job::where('id',$id)->first();
return view('candidate.apply');
Can someone help me because I am new to Laravel? and here is my main page where user click the button and redirect them to the form
<div class="col-md-2">
<div class="slide-btn">
Apply
</div>
</div
jobcontroller
public function index()
{
$jobs = Job::get();
$company = Company::get();
$menu = Menu::get();
$current_menu = 4;
// $jobs = Job::latest()->paginate(5);
$jobs = Job::
join('company', 'company.id', '=', 'jobs.company')
->get();
return view('jobs.joblist', compact('jobs', 'company', 'menu', 'current_menu'));
}
public function create()
{
return view('jobs.create');
}
public function store(Request $request)
{
$request->validate([
'company' => 'required',
'category' => 'required',
'position' => 'required',
'description' => 'required',
'salary_from' => 'required',
'salary_to' => 'required',
// 'status' => 'required|boolean',
]);
Job::create($request->all());
return redirect()->route('jobs.index');
}
public function show($id)
{
return view('jobs.show', compact('job'));
}
public function edit($id)
{
return view('jobs.edit', compact('job'));
}
public function update(Request $request, $id)
{
$request->validate([
'company' => 'required',
'category' => 'required',
'position' => 'required',
'description' => 'required',
'salary_from' => 'required',
'salary_to' => 'required',
]);
$jobupdate=Job::where('id',$id)->first();
$jobupdate->company=$request->company;
$jobupdate->category=$request->category;
$jobupdate->position=$request->position;
$jobupdate->description=$request->description;
$jobupdate->salary_from=$request->salary_from;
$jobupdate->salary_to=$request->salary_to;
$jobupdate->save();
// Job::update($request->all());
return redirect()->route('jobs.index');
}
public function destroy(Job $job)
{
$job->delete();
return redirect()->route('jobs.index');
}
public function active(Request $request)
{
// dd('text');
$job = Job::where('company',$request->jobId)->first();
$activeVal=request()->get('value');
// dd($activeVal);
if($activeVal == 1)
{
$activeVal=1;
}else{
$activeVal=0;
}
$job->status=$activeVal;
$job->save();
$output['success'] = 'success';
return response()->json($output, 200);
}
You need to pass data to the view using the second parameter of view.
$jobs = Job::get();
return view('candidate.apply', ['jobs' => $jobs]);
Add the compact function in laravel on your return statement.
$jobs = Job::get();
return view('candidate.apply', compact('jobs'));
I am working through creating a CRUD app in Laravel, I am using the default created_at and updated_at columns that seem to populate automatically when I insert or update to the database. When changing from using the edited entry's ID to pulling in the actual model entry as a parameter in my update method, I stumbled upon the exception "InvalidArgumentException
A four digit year could not be found Data missing" when calling $installer->update(['my field 1', ...]);
I have tried dd'ing my request and the $installer object that is pulled in and everything looks correct, but updating this way seems to break the update on the updated_at field. Below are the relevant snippets:
My model class:
class Installer extends Model
{
protected $guarded = [];
}
My update method:
public function update(Installer $installer) {
request()->validate([
'FirstName' => 'required',
'LastName' => 'required',
'Position' => 'required',
'Status' => 'required',
'EmpId' => 'required'
]);
$installer->update(['FirstName', 'LastName', 'Position', 'Status', 'EmpId']);
return redirect('/installers');
}
The relevant part of my edit form:
<form method="POST" action="/installers/{{ $installer->id }}" style="margin-bottom: 1em">
#method('PATCH')
#csrf
<div class="field">
<label class="label" for="FirstName">First Name</label>
<div class="control">
<input type="text" class="input" name="FirstName" placeholder="First Name" value="{{ $installer->FirstName }}" required>
</div>
</div>
<div class="field">
<label class="label" for="LastName">Last Name</label>
<div class="control">
<input type="text" class="input" name="LastName" placeholder="Last Name" value="{{ $installer->LastName }}" required>
</div>
</div>
<div class="field">
<label class="label" for=Position">Position</label>
<div class="control">
<input type="text" class="input" name="Position" placeholder="Position" value="{{ $installer->Position }}" required>
</div>
</div>
<div class="field">
<label class="label" for="Status">Status</label>
<div class="control">
<input type="text" class="input" name="Status" placeholder="Status" value="{{ $installer->Status }}" required>
</div>
</div>
<div class="field">
<label class="label" for="EmpId">Employee ID</label>
<div class="control">
<input type="text" class="input" name="EmpId" placeholder="Employee ID" value="{{ $installer->EmpId }}" required>
</div>
</div>
<div class="field">
<div class="control">
<button type="submit" class="button is-link">Update Installer</button>
</div>
</div>
</form>
How do I modify this so that eloquent will continue to update the updated_at field automatically?
Your update method is wrong
One easy way is try something like below:
public function update(Installer $installer) {
$validatedData = request()->validate([
'FirstName' => 'required',
'LastName' => 'required',
'Position' => 'required',
'Status' => 'required',
'EmpId' => 'required'
]);
$installer->update($validatedData); //or $installer->update([$validatedData]);
return redirect('/installers');
}
hope this is helpful
You are not including an array to the update method
Must be something like this:
$installer->update([
'FirstName' => $request->FirstName,
'LastName' => $lastNameVar,
'ColName' => $colValue,
...
]);
Where $request is the data from the
So I just made a syntax error but I figured I would leave this up if anyone has a similar issue. In my update method:
$installer->update(['FirstName', 'LastName', 'Position', 'Status', 'EmpId']);
should read:
$installer->update(request(['FirstName', 'LastName', 'Position', 'Status', 'EmpId']));
I have tried everything and I can't figure out where comes my mistake.
the update() method doesn't update anaything, i only get back "No message" error...
Here's Routes in web.php:
Route::get('/user/edit/{id}', ['as' => 'users.edit', 'uses' => 'UserAdController#edit']);
Route::post('/user/update/{id}', ['as' => 'users.update', 'uses' =>'UserAdController#update']);
the view users/edit.blade.php :
<div class="container">
<br>
<h3>Edit your ad</h3>
<br>
<form method="post" action="{{route('users.update', $ad->id)}}">
<input name="_method" type="hidden" value="PATCH">
{{ method_field('post') }}
<div class="form-group">
<label for="title">Title</label>
<input type="text" name="title" class="form-control" id="title" value="{{$ad->title}}">
</div>
<div class="form-group">
<label for="title">Price</label>
<input type="text" name="price" class="form-control" id="title" value="{{$ad->price}}">
</div>
<div class="form-group">
<label for="content">Your content</label>
<textarea name="content" class="form-control" id="content" rows="3">{{$ad->content}}</textarea>
</div>
<div class="form-group">
<input type="submit" value="Update" class="btn btn-info">
</div>
</form>
</div>
#endsection
Update method from UserAdController:
public function update($id, Request $request){
$request->validate([
'title'=>'required',
'price'=> 'required|integer',
'content' => 'required'
]);
$data = \App\Ad::find($id);
$data->title = $request->get('title');
$data->price = $request->get('price');
$data->content = $request->get('content');
$data->save();
return redirect()->back()->with('success', 'Data updated');
}
I'm not a laravel dev. I just stumbled on the documentation. You should also add the csrf field to your blade
In edit.blade.php, add this after the opening <form> tag
{{csrf_field()}}
Also the parameters in your update method aren't well arranged
It should be
public function update(Request $request, $id) {
}
The second parameter($id), comes from what you've defined as your routes in web.php file
Route::post('/user/update/{id}', ['as' => 'users.update', 'uses' =>'UserAdController#update']);
Where {id} would be replaced by the original id
Try this instead
public function update(Request $request){
//your code here
}
Request->only() returns an array with one element, While validator is the most common way to handle validation for the incoming request.
use Validator;
public function update(Request $request, $id){
$v = validator($request->only('title', 'price', 'content'), [
'title' => 'required|string|max:255',
'price' => 'required|integer',
'content' => 'required',
]);
$data = request()->only('title','price','content');
$userData = ([
'title' => $data['title'],
'price' => $data['price'],
'content' => $data['content'],
]);
$data = \App\Ad::find($id);
$data->update($userData);
return response()->json($data);
}
Thank you all !!
Seems like I wasn't doing it right.
I needed to add {{csrf_field()}} in edit form and use $request->only()
I think it would be better if you use put method like this:
Route::put('ad/{ad}', ['as' => 'users.update', 'uses' =>'UserAdController#update']);
update your form to be like this:
<div class="container">
<br>
<h3>Edit your ad</h3>
<br>
<form method="post" action="{{route('users.update', ['ad' => $ad->id])}}">
<input name="_method" type="hidden" value="PATCH">
{{ method_field('put') }}
{{ csrf_field() }}
<div class="form-group">
<label for="title">Title</label>
<input type="text" name="title" class="form-control" id="title" value="{{$ad->title}}">
</div>
<div class="form-group">
<label for="title">Price</label>
<input type="text" name="price" class="form-control" id="title" value="{{$ad->price}}">
</div>
<div class="form-group">
<label for="content">Your content</label>
<textarea name="content" class="form-control" id="content" rows="3">{{$ad->content}}</textarea>
</div>
<div class="form-group">
<input type="submit" value="Update" class="btn btn-info">
</div>
</form>
and now your update function :
public function update(\App\Ad $ad, Request $request){
$request->validate([
'title'=>'required',
'price'=> 'required|integer',
'content' => 'required'
]);
//$data = \App\Ad::find($id);
$ad->update([
"title" => $request->title,
"price" => $request->price,
"content" => $request->content,
]);
return redirect()->back()->with('success', 'Data updated');
}
when you get use to put, delete and patch methods you can read about Route::resource and your code will be easier.
So i'm working with laravel 5.4 and i'm stuck in this error and can't figure it out.I researched about this error and i've seen that this happened before to, but the solutions are not working on my project.
I created a form to add comments in my page and it works if i type something it saves it in database and validation is working to because its not letting me add empty comment but its not showing the errors in page.
This is the comment form in views
<form method="post" action="{{ route('comments.store') }}">
{{ csrf_field() }}
<input type="hidden" name="commentable_type" value="App\Company">
<input type="hidden" name="commentable_id" value="{{ $company->id }}">
<h2>Add a comment</h2>
<div class="form-group #if($errors->has('url')) has-error #endif">
<label for="comment-content">Work done (url/title)</label>
<textarea placeholder="Enter url/title"
style="resize: vertical;"
id="comment-content"
name="url"
rows="2"
spellcheck="false"
class="form-control autosize-target text-left">
</textarea>
</div>
<div class="form-group #if($errors->has('body')) has-error #endif">
<label for="comment-content">Comment</label>
<textarea placeholder="Enter comment"
style="resize: vertical;"
id="comment-content"
name="body"
rows="3"
spellcheck="false"
class="form-control autosize-target text-left">
</textarea>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Submit"/>
</div>
</form>
This is the CommentsControlles.php
public function store(CommentSubmitFormRequest $request)
{
$comment = Comment::create([
'body' => $request->input('body'),
'url' => $request->input('url'),
'commentable_type' => $request->input('commentable_type'),
'commentable_id' => $request->input('commentable_id'),
'user_id' => Auth::user()->id
]);
if ($comment)
{
return back()->with('success', 'Comment added successfully');
}
}
And this is the Request CommentSubmitFormRequest.php
class CommentSubmitFormRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'body' => 'required',
'url' => 'required',
];
}
}
When i submit the empty comment form the $errors is returning null and not the errors
Your validation rules are incomplete. It only said to be required and in your case your body and url are sent because the fields do exists. You should set a minimum amount of characters or do active_url/url for the url field.
public function rules()
{
return [
'body' => 'required|min:1', // minimum length of 1 character
'url' => 'required|url', // must be a valid URL
];
}