Laravel edit form can't update child/parent row - php

Im new to laravel and i want to make an update function but it doesn t work. I get my update form correctly but when i submit it i get an error that says it can t updata a parent/child row
This is my function
public function update($verhaal, $wereld)
{
$wereld = Werelden::where('wereld_id', $wereld)->update([
'wereld_id' => $wereld,
'naam' => 'naam',
'beschrijving' => 'beschrijving',
'verhaal_id' => 'verhaal_id'
]);
return redirect('/');
}
This are my routes
Route::get('verhalen/{verhaal}/bekijken/{wereld}/edit', 'WereldController#BewerkWereld');
Route::put('verhalen/{verhaal}/bekijken/{wereld}/edit', 'WereldController#update');
And as last i have my html form
<div class="panel-body">
#include('common.errors')
<form action="{{ url('/verhalen/'. $wereld->verhaal_id .'/bekijken/'. $wereld->wereld_id .'/edit')}} " method="POST">
{{ csrf_field() }}
{{ method_field('PUT') }}
<input type="text" class="form-control verhaal-toevoegen" value="{{ $wereld->naam }}" name="naam">
<textarea class="form-control" id="verhaal-text" name="verhaal">{{ $wereld->beschrijving}}</textarea>
<button type="submit" class="btn btn-primary">Verhaal bijwerken</button>
</form>
</div>
I hope someone can help me

public function update($verhaal, $wereld)
{
$wereld = Werelden::where('wereld_id', $wereld)->update([
'wereld_id' => $wereld,
'naam' => 'naam',
'beschrijving' => 'beschrijving',
'verhaal_id' => $verhaal_id // "verhaal_id" It is not an id
]);
return redirect('/');
}
uses columns necesaries only
$wereld = Werelden::where('wereld_id', $wereld)->update([
'wereld_id' => $wereld,
'naam' => 'naam',
'beschrijving' => 'beschrijving',
]);

Related

Populating edit form with db data returns Undefined variable Error - Laravel 7

I am working in Laravel 7 trying to auto populate form data from the db using value="{{ $task->task_name }}" for example. but it is throwing an Undefined Variable: task in my edit.blade.php file.
I am getting the right task id as I can see it in the url. I have tried {{ old('task_name') }} and that just returned a the placeholder in the input field with no error. if I put {{ old('task_name', $task->task_name) }} it also throws an error. If anyone can help out with this issue, I would certainly appreciate it. I am using resources for my functions. Here is the code so far:
edit.blade.php (just relevant portion)
<form method="POST" action="tasks/{$id}" id="editForm" enctype="multipart/form-data" class="mb-5">
{{ csrf_field() }}
{{ method_field('PUT') }}
<div class="form-group">
<input
id="task_name"
type="text"
name="task_name"
class="form-control"
placeholder="Task name"
value="{{ $task->task_name }}" />
</div>
...
<button type="submit" class="btn btn-success float-right">Edit Task</button>
</form>
In my tasks.blade.php (edit button only)
<div class="float-right" style="display: inline;">
<a href="tasks/{{$task->id}}/edit" class="btn btn-primary mb-3 ml-2">
<i class="fa fa-edit"></i> Edit
</a>
</div>
Finally, my TaskController.php
public function edit($id)
{
return view('tasks.edit');
}
public function update(Request $request, $id)
{
$this->validate($request, [
'task_name' => 'required',
'task_description' => 'required',
]);
$task = Task::find($id);
$task->task_name = $request->input('task_name');
$task->task_description = $request->input('task_description');
$task->task_priority = $request->input('task_priority');
$task->task_assigned_by = $request->input('task_assigned_by');
$task->task_assigned_to = $request->input('task_assigned_to');
$task->task_to_be_completed_date = $request->input('task_to_be_completed_date');
$task->task_notes = $request->input('task_notes');
$task->task_status = $request->input('task_status');
$task->update();
return redirect('/tasks')->with('success', 'Task Updated');
}
If I am missing any code or if you have any questions that would shed light on my query, please let me know so I can update my question. Thank you again in advance.
You need to pass the $task variable into the view:
public function edit($id)
{
$task = Task::findOrFail($id);
return view('tasks.edit', ['task' => $task]);
}
Also, you can use the request validation method to extract the inputs that you need, after that, everything will be in the $data variable and you can easily update your model with one line of code.
I don't know how do you expect to receive the data, so I use nullable for the validation entries, you can take a look into all validations here: https://laravel.com/docs/7.x/validation
public function update(Request $request, $id)
{
$task = Task::findOrFail($id);
$data = $request->validate([
'task_name' => 'required',
'task_description' => 'required',
'task_priority' => 'nullable',
'task_assigned_by' => 'nullable',
'task_assigned_to' => 'nullable',
'task_to_be_completed_date' => 'nullable',
'task_notes' => 'nullable',
'task_status' => 'nullable',
]);
$task->update($data);
return redirect('/tasks')->with('success', 'Task Updated');
}
This code will make the same this as the other, but it's much cleaner in my opinion.

Update article laravel

Controller article
public function update(Request $request, Article $article){
$article->update($request->except('slug', 'image_path'));
if ($request->hasFile('image_path')) {
$image = $request->file('image_path');
$new_name = rand() . '.' . $image->getClientOriginalExtension();
$image->move(public_path('images'), $new_name);
$article->image_path = $new_name;
$article->save();
}
$article->categories()->detach();
if ($request->has('categories')) {
$article->categories()->attach($request->input('categories'));
}
$user=auth()->user();
return redirect()->back()->with('message', 'Raksts atjaunots!');
}
public function edit(Article $article){
$user=auth()->user();
return view('edit',[
'article' => $article,
'categories' => Category::with('children')->where('parent_id',0)->get(),
'delimiter' => ''
]);
}
edit blade
<form class="form-horizontal" action="{{route('update', $article)}}" method="post" enctype="multipart/form-data" style="display: flex;justify-content: center;flex-direction: column;">
<input type="hidden" name="_method" value="put">
{{ csrf_field() }}
{{-- Form include --}}
<img src="{{URL::to('/images').'/'.$article->image_path}}" alt="">
#include('partials.form')
<input type="hidden" name="modified_by" value="{{Auth::id()}}">
</form>
link to the form
<tbody>
#foreach ($articles_suggest_user as $article)
<a class="btn btn-default" href="{{route('edit', $article)}}"><i class="fa fa-edit"></i></a>
<?php } ?>
#endforeach
</tbody>
web.php
Route::get('/home/edit/{id}','Controller_Article_parents#edit', function () {
return view('/home/edit');
})->name('edit');
Route::get('/home/update/','Controller_Article_parents#update', function () {
return view('/home');
})->name('update');
When i clicked the link, i move to for example this url http://127.0.0.1:8000/home/edit/190
But my form is empty... input empty. How I can do when I open form it's display me input information ?
When click my link its display me form, but form is empty.
form example
<div class="rtq">
<label for="parent_id">Cat</label>
<span class="required">*</span>
<select
id="parent_id"
class="form-control"
name="categories[]"
multiple=""
required
>
#include('admin.categories.partials.categories',
['categories' => $categories,
'current' => $article,
'delimiter' => $delimiter])
</select>
</div>
<div class="rtq">
<label for="">Descript</label>
<textarea
name="description_short"
class="form-control"
id="description_short"
>
{{ $article->description_short ?? "" }}
</textarea>
</div>
It my form . Mini example
If you want to redirect with form input, you can use the withInput() function
return back()->withInput();
https://laravel.com/docs/7.x/redirects#creating-redirects
Now, this function is designed to be used with form validation and may not be what you want.
What I have done in the past when combining create & edit views into a single template is something like this:
{!! Form::text('name', isset($model) ? $model->name : null, [
'class' => 'form-control',
'placeholder' => 'Please fill out this field &hellips;',
'required' => true
]) !!}
This uses the Laravel Collective HTML library. However the principle is the same if you are using raw hmtl like so:
<input type="text" value="{{ isset($model) ? $model->name : null }}">
Round 2 Electric Boogaloo
You aren't returning a variable called $article to your edit.blade.php.
Round 3 Apple Tree
Originally, you appeared to be calling both a controller action AND also a callback function. Stick to the controller action only like so:
Route::get('/home/edit/{id}','Controller_Article_parents#edit')->name('edit');
Then within your edit() function on the Controller you will want to do this:
public function edit ($id) {
return view('/home/edit', [
'article' => Article::find($id)
]);
}

Laravel Form with multiple select

I have the following controller, which sends data to a Laravel Blade view:
Controller:
public function create()
{
$schools = School::all()->sortBy('school_type');
return view('invoices.create')->with([
'schools' => $schools,
'dayTypes' => $dayTypes,
]);
}
In that Laravel blade view there is a form:
<form method="GET" action="{{ route('invoices.choose-periods') }}">
<div class="form-group {{ $errors->has('school') ? 'has-error' : '' }}">
<label>School</label>
<select id="school" class="form-control" name="school[]" multiple size="{{ $schools->count() }}" required>
#foreach ($schools as $school)
<option value="{{ $school->id }}">{{ $school->name }}</option>
#endforeach
</select>
#if ($errors->has('school'))
<span class="help-block">
<strong>{{ $errors->first('school') }}</strong>
</span>
#endif
</div>
<button type="submit" class="btn btn-success btn-sm pull-right">Submit</button>
</form>
As you can see from the HTML, the form is a multi-select form, with the resulting data stored in a school[] array.
On submission of the form, I do a test die and dump on request('school') and see that for every option I have selected, the value seems to have been logged twice. For example, choosing only one option gives me:
array:2 [▼
0 => "15"
1 => "15"
]
Any ideas? Thanks!
I have only worked on laravel 5.7. Try this It is working for me.
Since you are passing 2 objects
return view('invoices.create')->with([
'schools' => $schools,
'dayTypes' => $dayTypes,
]);
It is obvious you will get 2 errors.
In your controller change this
public function create()
{
$schools = School::all()->sortBy('school_type');
return view('invoices.create')->with([
'schools' => $schools,
'dayTypes' => $dayTypes,
]);
}
to this
public function create(){
$schools = School::all()->sortBy('school_type');
return view('invoices.create', ['schools' => $schools]),
]);
}

How to put input textarea in an array? (Laravel 5.3)

My view blade is like this :
#foreach($reviews as $key => $review)
...
<div class="form-group">
{!! Form::open(['route' => 'message.review.update', 'method' => 'post', 'id' => 'reviewform']) !!}
<label for="review" class="sr-only">Review</label>
{!! Form::textarea('review', null, ['class' => 'form-control', 'id' => 'review', 'rows'=>3,'required'=>'required']) !!}
#if ($errors->has('review'))
<span class="help-block">
<strong>{{ $errors->first('review') }}</strong>
</span>
#endif
{!! Form::hidden('id', $review->_id) !!}
{!! Form::hidden('store', $review->store_id) !!}
{!! Form::close() !!}
</div>
...
#endforeach
My routes is like this :
Route::group(['prefix' => 'message','as'=>'message.'],function(){
Route::post('review/update', ['as'=>'review.update','uses'=>'ReviewController#update']);
});
My controller to update is like this :
public function update(CreateReviewRequest $request)
{
$param = $request->only('id', 'review', 'store');
...
}
Before update, it will call CreateReviewRequest to validation
My CreateReviewRequest is like this :
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class CreateReviewRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'review'=>'required|max:300'
];
}
}
When, only one data, I input comment and submit, it works
But, when more than one data, it does not works
There exist error like this :
An invalid form control with name='review' is not focusable.
How can I solve it?
You made some mistakes here... In HTML IDs MUST be unique. You can't put "review" as id for all your textareas... My comment was about to use an array as name like this name=review[], and in the ID add dynamically the $key at the end of the id to make them unique.
This will give you something like this :
<textarea name="review[]" class="form-control" id="review0" rows="3" required></textarea>
<textarea name="review[]" class="form-control" id="review1" rows="3" required></textarea>
<textarea name="review[]" class="form-control" id="review2" rows="3" required></textarea>
EDIT
I've just founded this stackoverflow topic. Could you try to add novalidate attribute in the <form>?
<form name="myform" novalidate>
Something like this in your case :
{!! Form::open(['route' => 'message.review.update', 'method' => 'post', 'id' => 'reviewform', 'novalidate']) !!}
VIEW
{!! Form::textarea('review[]', null, ['class' => 'form-control', 'id' => 'review', 'rows'=>3,'required'=>'required']) !!}
or
<textarea name="review[]" class="form-control" id="review" rows="3" required></textarea>
You must insert name field like array empty, when you will submit the form you can get all values in your controller calling:
CONTROLLER
public function update(Request $request)
{
// Validate the form
$this->validate($request, [
'review' => 'required',
]);
// get inputs
$review_input = $request->get('review');
dd($review_input); // see if it work
}

Argument 2 passed to Controller method must be in instance of Request, none given

I'm trying to pass 2 dates from one view to another, in my controller, but I get the following error:
Argument 2 passed to App\Http\Controllers\GuestController::reservationToGuest() must be an instance of Illuminate\Http\Request, none given
This is my first view (the view having the date):
<form action="{{ route('create_guest') }}">
{{ csrf_field() }}
<input type="hidden" value="2016-08-26" name="dateOne">
<input type="hidden" value="2016-08-28" name="dateTwo">
<button class="btn btn-block btn-success">Proceed To Check In</button>
</form>
(dateOne and dateTwo are the dates which I want in the second view)
routes.php
Route::get('/guest_page/create/{idreservation?}',[
'uses' => 'GuestController#reservationToGuest',
'as' => 'create_guest'
]);
reservationToGuest in GuestController
public function reservationToGuest($idreservation = null, Request $request){
if($idreservation === null){
return view('guest_page_create', ['idreservation' => 0, 'page_title' => 'Guest Check In', 'check_in_date' => $request['dateOne']]);
} else{ //else clause works just fine and the dates from the database are inserted into the view
$details = DB::table('reservation')
->where('idreservation', $idreservation)
->get();
return view('guest_page_create', ['idreservation' => $idreservation, 'details' => $details, 'page_title' => 'Guest Check In']);
}
}
And in view 'guest_page_create'
<label for="datemask">Check In Date</label>
<input type="date" class="form-control" id="datemask" name="datemask" value="{{ $check_in_date }}">
You shouldn't pass optional parameters before required ones. Try this:
public function reservationToGuest(Request $request, $idreservation = null)
{
// ...
}

Categories