Laravel Form with multiple select - php

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]),
]);
}

Related

Cant show old value and edit value in PHP Laravel

How to show an old value / query field from database in mysql, and edit value in Laravel. I'm using Laravel 9x and PHP 8x
Controller.php :
public function edit(Business $business)
{
return view('dashboard.bisnis.edit', [
'item' => $business
]);
}
public function update(Request $request, Business $business)
{
$rules = [
'deskripsi' => 'required|max:255',
'pemilik' => 'required|max:255'
];
$validateData = $request->validate($rules);
Business::where('id', $business->id)->update($validateData);
return redirect('/dashboard/bisnis')->with('success', 'Item has been updated !');
}
Blade.php:
#extends('dashboard.index')
#section('container')
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
<h1 class="h2">Edit Data Bisnis</h1>
</div>
<div class="col-lg-8">
<form method="post" action="/dashboard/bisnis/{{ $item->id }}" class="mb-5" enctype="multipart/form-data">
#method('put')
#csrf
<div class="mb-3">
<label for="deskripsi" class="form-label">Deskripsi</label>
<input type="text" class="form-control #error('deskripsi') is-invalid #enderror" id="deskripsi" name="deskripsi" required autofocus
value="{{ old('deskripsi', $item->deskripsi) }}">
#error('deskripsi')
<div class="invalid-feedback">
{{ $message }}
</div>
#enderror
</div>
<div class="mb-3">
<label for="pemilik" class="form-label">Pemilik</label>
<input type="text" class="form-control #error('pemilik') is-invalid #enderror" id="pemilik" name="pemilik" required autofocus
value="{{ old('pemilik', $item->pemilik) }}">
#error('pemilik')
<div class="invalid-feedback">
{{ $message }}
</div>
#enderror
</div>
<button type="submit" class="btn btn-primary">Simpan Perubahan</button>
</form>
</div>
<script>
const deskripsi = document.querySelector('#deskripsi');
const pemilik = document.querySelector('#pemilik');
</script>
#endsection
Also when navigating through my menu such as Business, the sidebar seems cant to be clicked, nor use. Thank you so much
Please try like this:
{{ old('deskripsi') ? old('deskripsi') :$item->deskripsi }}
Please replace this:
return redirect('/dashboard/bisnis')->with('success', 'Item has been updated !');
to
return redirect()->back()->with('success', 'Item has been updated !');
I assume you use Laravel 9
Referring to Repopulating Forms - Validation
Controller.php:
you should use
$deskripsi = $request->old('deskripsi');
$pemilik = $request->old('pemilik');
before
$validateData = $request->validate($rules);
Blade.php:
you should use this on input
value="{{ old('deskripsi') }}"
value="{{ old('pemilik') }}"
By default old will return null if no input exists so we don't need to use nullcheck like
{{old('deskripsi') ?? ''}}
To repopulate value using old() in Laravel you need to return a response withInput(). Not just response.
The return code should
return redirect('/dashboard/bisnis')->with('success', 'Item has been updated !');
change to this
return redirect('/dashboard/bisnis')->with('success', 'Item has been updated !')->withInput();
The solution is i forgot to pass my $id on my controller and route (web.php). Here's my route
Route::controller(GroupServiceController::class)->middleware('auth')->group(function () {
Route::get('/dashboard/gruplayanan', 'index');
Route::get('/dashboard/gruplayanan/create', 'create')->name('gruplayanan.create');
Route::post('/dashboard/gruplayanan', 'store')->name('gruplayanan.store');
Route::get('/dashboard/gruplayanan/edit/{id}', 'edit')->name('gruplayanan.edit');
Route::post('/dashboard/gruplayanan/update/{id}', 'update')->name('gruplayanan.update');
Route::post('/dashboard/gruplayanan/delete/{id}', 'destroy')->name('gruplayanan.delete');
});
and my controller :
public function edit(GroupService $groupService, $id)
{
$groupService = $groupService->findOrFail($id);
return view('dashboard.gruplayanan.edit', [
'item' => $groupService
]);
}

Laravel Livewire update array checkbox. ( Edit Form )

i stack with livewire Update with checkbox array please help.
Form
<form wire:submit.prevent="Update" class="py-3 mb-6">
#foreach ($permissions as $key => $pms)
<input type="checkbox" model:wire="PermissionCheckbox.{{ $key }}" {{ in_array($pms->id , $PermissionCheckbox)? "checked":"" }} />
#endforeach
<button class="btn btn-primary" type="submit">Update</button>
</form>
Php Function
public function Edit($id){
$role = Role::find($id);
$this->roleId = $role->id;
$this->roleName = $role->name;
$this->PermissionCheckbox = json_decode($role->permissions->pluck('id'));
}
public function Update(){
$this->validate([
'roleName' => 'sometimes|required|unique:roles,name,'.$this->roleId,
'PermissionCheckbox' => 'required'
]);
dd($this->PermissionCheckbox);
}
The result not update with the PermissionCheckbox.
Thank you in advance guys.
check your input because it has the wire model inverted
the correct is wire:model
<input type="checkbox" wire:model="PermissionCheckbox.{{ $key }}" {{ in_array($pms->id , $PermissionCheckbox)? "checked":"" }} />

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 edit form can't update child/parent row

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',
]);

Search and Pagination Laravel 4

I have a problem, I want to use the form to do a search and use pagination. The problem is when I change the page, an error occurs:
No query results for model [Aluno].
My controller
Route::post(
'alunos/busca',
array(
'as' => 'alunos.busca',
'uses' => 'AlunosController#busca'
)
);
My Controller
public function busca()
{
$search = Input::get('q');
$alunos = Aluno::where('curso', $search)->paginate(1);
return View::make('alunos.index', compact('alunos', 'search'));
}
My view:
<form method="post" action="{{ URL::to('alunos/busca') }}">
<input class="input-xxlarge" name="q" type="text" placeholder="Search...">
<div class="control-group">
<div class="controls">
<input type="submit" class="btn" id="submit" value="Submit" />
</div>
</div>
<div class="divPagination">
{{ $alunos->links() }}
</div>
I need help..
Sorry my English
I think the best solution is the next one:
Copy and paste this form wherever you want it:
{{Form::open(array('url' => 'alunos/busca','method' => 'get'))}}
{{Form::text('q', null , array('placeholder' => 'Search...','class' => 'input-xxlarge'))}}
{{Form::submit('SEARCH',array('class' => 'btn','id' => 'submit'))}}
{{Form::close()}}
In routes.php :
Route::get('alunos/busca', function() {
$search = Input::get('q');
$alunos = Aluno::where('curso', 'LIKE', '%'.$search.'%')->paginate(15);
return View::make('alunos.index')
->with('alunos', $alunos);
});
Now, in your view app/views/alunos/index.blade.php :
#if(!$alunos->isEmpty())
#foreach($alunos as $aluno)
{{$aluno->subject}}
#endforeach
{{$alunos->links()}}
#else
<h1> No results </h1>
#endif
Change it as you wish and enjoy
The problem is when you click on the next page it has no memory of the search param you just entered, essentially $q = null; which will cause the error.

Categories