Laravel return old input of checkbox array - laravel

Edit: my $id contains an array
#php($ids = array('Fruit','Vegetables')
I just want to display the old input of my checkbox and textarea when the page returns with errors based on my validations.
Here is the form elements. I tried using the old(method) but its not working for me.
<form method = "post" action = "tomyController">
<input type = "text" name = "vendor" >
#foreach($ids as $id)
<input type = "checkbox" name = "check[{{$id}}][0]" value = "0">
<input type = "checkbox" name = "check[{{$id}}][1]" value = "1">
<textarea name = "remarks[{{id}}]"></textarea>
#endforeach
</form>
I tried the How to show old data of checkbox in Laravel? but didnt work on mine.
Here is how i implemented it.
<form method = "post" action = "tomyController">
#foreach($ids as $id)
<input type = "checkbox" name = "check[{{$id}}][0]" value = "0"
#if(is_array(old('check[$id][0]')) && in_array(0, old('check[$id][0]'))) checked #endif)>
<input type = "checkbox" name = "check[{{$id}}][1]" value = "1"
#if(is_array(old('check[$id][1]')) && in_array(1, old('check[$id][1]'))) checked #endif)>
<textarea name = "remarks[{{id}}]">{{ old('remarks[$id]') }}</textarea>
#endforeach
</form>
My controller code is here.
public function store(Request $request) {
$post = $request->all();
$validator = Validator::make($request->all(), [
"vendor" => "required",
]);
if ($validator->fails()) {
return redirect()->back()
->withErrors($validator)
->withInput($post);
}
else
#my other codes
}
dd($request)

Change your form to the following-
<form method = "post" action = "tomyController">
#foreach($ids as $id)
<input type = "checkbox" name = "check[{{$id}}][0]" value = "0"
#if(is_array(old('check['.$id.']')) && (0==old('check['.$id.'][0]'))) checked #endif>
<input type = "checkbox" name = "check[{{$id}}][1]" value = "1"
#if(is_array(old('check['.$id.']')) && (1== old('check['.$id.'][1]'))) checked #endif>
<textarea name = "remarks[{{$id}}]">{{ old('remarks['.$id.']') }}</textarea>
#endforeach
</form>

Related

Livewire checkboxes selected by default

What I would like :
By default check all checkboxes
Get the value sheet id for later
First issue :
Is it possible to sort / order them by id ?
Because for the moment it orders them by the order of check.
screenshot 2
If someone can help me I would be glad thanks :D
Here is my view :
#foreach($sheets as $sheet)
<div class="inputGroup">
<input id="{{$loop->index}}" wire:model="selectedBoxes" type="checkbox" value="{{$loop->index}}" checked/>
<label for="{{$loop->index}}">Feuille {{$loop->index+1}}: {{$sheet}}</label>
</div>
#endforeach
Here are the results when I dd($sheets) :
^ array:4 [▼
0 => "All ValueRAM FURY"
1 => "Non-ECC ValueRAM"
2 => "All FURY"
3 => "KSM (Server Premier)"
]
Here is my component :
public $sheets = [];
public $selectedBoxes = [];
...
public function readExcel()
{
...
$data = [];
// Return an import object for every sheet
foreach($import->getSheetNames() as $index => $sheetName)
{
$data = $import->getSheetNames();
$this->sheets = $data;
}
}
Website view :
screenshot 1
welcome to StackOverflow! You could remove the checked tag from your select and let wire:model do it's thing:
public $sheets = [
0 => "All ValueRAM FURY",
1 => "Non-ECC ValueRAM",
2 => "All FURY",
3 => "KSM (Server Premier)"
];
// wire:model will ensure that all are checked by default.
public $selectedBoxes = [true, true, true, true];
and in your view:
(Take a look at the wire:model property and the checked attribute is gone)
#foreach($sheets as $sheet)
<div class="inputGroup">
<input id="sheet-{{$loop->index}}"
wire:model="selectedBoxes.{{ $loop->index }}"
type="checkbox"
value="{{$loop->index}}" />
<label for="sheet-{{$loop->index}}">Feuille {{$loop->index+1}}: {{$sheet}}</label>
</div>
#endforeach
Thanks to Laisender I finded what I wanted.
What changed in my component :
public $counter = 0;
...
foreach($import->getSheetNames() as $index => $sheetName)
{
$data = $import->getSheetNames();
$this->sheets = $data;
array_push($this->selectedBoxes, "$this->counter");
$this->counter += 1;
}
My view :
#foreach($sheets as $sheet)
<div class="inputGroup">
<input id="sheet-{{$loop->index}}" wire:model="selectedBoxes.{{$loop->index}}" type="checkbox" value="{{$loop->index}}"/>
<label for="sheet-{{$loop->index}}">Feuille {{$loop->index+1}}: {{$sheet}}</label>
</div>
#endforeach

How to insert record in 2 tables using single form (Laravel)?

CONTROLLER
public function store_resto(Request $request){
// dd($request->all());
$restaurant = new Restaurant();
$restaurant->name = $request->input('name');
$restaurant->email = $request->input('email');
$restaurant->address = $request->input('address');
$restaurant->save();
$image = $request->hasfile('image');
$photo = rand(1,9999).'.'.$image;
$path = public_path().'/files/';
$image->move($path, $photo);
RestoImage::create([
'image'=>$image,
'resto_id'=>$restaurant->id,
]);
$request->session()->flash('status', 'Restaurant added successfully');
return redirect('list');
}
VIEW FILE
<form method="post" action="{{route('store_resto')}}" enctype="multipart/form-data">
#csrf
<div class="form-group">
<label>Resto Name</label>
<input type="name" name="name" class="form-control">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" name="email" class="form-control">
</div>
<div class="form-group">
<label>Address</label>
<input type="text" name="address" class="form-control">
</div>
<div class="form-group">
<label>Image</label>
<input type="file" name="image" class="form-control">
</div><br>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
RestoImage Model
class RestoImage extends Model
{
use HasFactory;
protected $fillable = ['image','resto_id'];
public function restaurants(){
$this->belongsTo(Restaurant::class, 'resto_id');
}
}
Restaurant Model
class Restaurant extends Model
{
use HasFactory;
public $timestamps = false;
public function menus(){
$this->hasMany(Menu::class);
}
public function restoimage(){
$this->hasOne(RestoImage::class, 'resto_id');
}
}
Each restaurant will have 1 image. When an admin submits the form, 1 record should be inserted in both tables i.e. restaurants and resto_images. I tried this way but when I submit the form, It shows error "Call to a member function move() on bool". Please correct me if I am doing wrong. Thanks in advance.
Here i Worked on your code to explain how these things works.This is an example can help you. Not for two you can add so many tables from one function of controller. Approve my answer if you find solution or reason for getting error.
You have error because code doesn't find your image format or mine:type(png, jpeg)
$photo = rand(1,9999).'.'.$image;
Solution- you have to get image format or extention by this code
$extention = $emp_image_file->getClientOriginalExtension();
Your solution should be like this
$path1 = 'assets/img/emp/';
$destinationPath1 = $path1;
$photo_file = $request->file('image');
$photo='';
if($photo_file){
$file_size = $photo_file->getSize();
$image_name = $photo_file->getClientOriginalName();
$extention = $photo_file->getClientOriginalExtension();
$photo = value(function() use ($photo_file){
$filename = time().'.'. $photo_file->getClientOriginalExtension();
return strtolower($filename);
});
$photo_file->move($destinationPath1, $photo);
}
Put js in your view file
<script type="text/javascript">
function readURL(input) {
if (input.image && input.image[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#imagePreview').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
</script>
This is you input
<input type="file" class="form-control" name="image" >
I Also Worked For Other Visitors See Once
public function store_resto(Request $request){
<!-- validation code begins -->
$this->validate($request, [
'name'=>'required|max:120',
'email'=>'required|email|unique:users',
]);
<!-- validation code ends -->
$data = $request->all();
$table1 = Required_Model1::create([
'name' =>$data['emp_name'],
'email' =>$data['email'],
]);
$table2 = Required_Model2::create([
'name' => $data['emp_name'],
'code' => $data['emp_code'],
'status' => $data['emp_status'],
'email' => $data['email'],
'gender' => $data['gender'],
'table1_id' => $table1->id,
]);
$table3 = Required_Model3::create([
'role' => $data['role'],
'table1_id' => $table1->id,
'table2_id' => $table2->id,
if(isset($table1, $table2, $table3)) {
$request->session()->flash('status', 'Restaurant added successfully');
return redirect()->route('employee-manager');
}else{
return redirect()->back();
}
}
Comment or delete this part of code if you doesn't want to validate or mandatory.
$this->validate($request, [
'name'=>'required|max:120',
'email'=>'required,
]);
Above code explains
column name must be filled with 120 characters or not be blank.
column email must be filled.
if these two doesn't satisfy it will redirect back.
This below code
If validation is set like above code this will check and work as defined. If validation is set they check two fields name and email, if they filled or not blank it will proceed further. If validation is set fields are not filled or blank they redirect back. If validation is not set it will proceed further.
if(isset($table1, $table2, $table3)) {
$request->session()->flash('status', 'Restaurant added successfully');
return redirect()->route('employee-manager');
}else{
return redirect()->back();
}
Change these two lines
<input type="name" name="name" class="form-control" required="true" />
<input type="email" name="email" class="form-control" required="true" />
Model 1 should be like this
class Required_Model1 extends Model
{
protected $fillable = ['name','email'];
}
Model 2 should be like this
class Required_Model2 extends Model
{
protected $fillable = ['name','code', 'status', 'email', 'gender', 'table1_id'];
}
Model 3 should be like this
class Required_Model3 extends Model
{
protected $fillable = ['role','table1_id', 'table2_id'];
}
Let's talk on your error as you posted
You have face error because you want to move your image name in form of boolean. Here is gave you an standard code you can use it
$path1 = 'assets/img/emp/';
$destinationPath1 = $path1;
$emp_image_file = $request->file('employee_images');
$emp_image='';
if($emp_image_file){
$file_size = $emp_image_file->getSize();
$image_name = $emp_image_file->getClientOriginalName();
$extention = $emp_image_file->getClientOriginalExtension();
$emp_image = value(function() use ($emp_image_file){
$filename = time().'.'. $emp_image_file->getClientOriginalExtension();
return strtolower($filename);
});
$emp_image_file->move($destinationPath1, $emp_image);
}
Put this in which table you wanted to save
'photo' => $emp_image,
Add this in your view make sure you edit like your requirement
<script type="text/javascript">
function readURL(input) {
if (input.employee_images && input.employee_images[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#employee_imagesPreview').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
</script>
This is input
<input type="file" class="form-control" name="employee_images" >
$image = $request->hasfile('image');
This method is a boolean method. It will return true/false. Instead use
$request->file('image');
So first, here:
$image = $request->hasfile('image');
You are setting $image to a boolean by checking if it has that file and then later you want to run move on a that boolean which is not possible. Rather do:
if($request->hasfile('image'))
{
$image = $request->file('image');
$image->move($path, $photo);
}

Property [costo] does not exist on this collection instance

i need to print the price of a service, but can't find the column with the price.
maybe I'm doing something wrong with relationships, but I can't figure it out on my own
database:
Controller:
public function details(Request $request,$id){
$datax = [
'category_name' => 'apps',
'page_name' => 'calendar',
'has_scrollspy' => 0,
'scrollspy_offset' => '',
];
$evento = Eventos::find($id);
$servicio = \App\Models\Eventos::select("servicio_id")->where('servicio_id', $evento->id)->get('servicio_id');
$event = Eventos::find($id);
$event->asistencia = $request->asistencia;
$event->cancelado = $request->cancelado;
$event->save();
return view("evento",[
"event" => $event,
"servicio" => $servicio
])->with($datax);
}
blade.php
<div class="input-group mb-4">
<div class="input-group-prepend">
<span class="input-group-text">$</span>
</div>
<input type="text" value="{{$servicio->costo}}" class="form-control col-md-3" aria-label="Amount (to the nearest dollar)">
<div class="input-group-append">
<span class="input-group-text"></span>
</div>
</div>
I need to print the "costo" column in relation to service_id
help please
you can use laravel elequent relationship one to one.
if you have this two Servicio.php & Evento.php in App/Models or whatever your models name is, only replace your models in below code do this:
1-
in App/Models/Servicio.php define this relationship:
public function evento()
{
return $this->hasOne(Evento::class);
}
in App/Models/Evento.php define this relationship:
public function servicio()
{
return $this->belongsTo(Servicio::class);
}
now in controller add this:
$evento = Eventos::where('id' , $id)->with('servicio')->first();
in blade use this:
<input type="text" value="{{$evento->servicio->costo}}" >
2- also you can do this but i suggest you the first one:
only in your Codes change this:
$servicio = \App\Models\Servicio::where('id', $evento->servicio_id)->first();

How to fix 'Failed to load resource: the server responded with a status of 500 (Internal Server Error)' when i used fetch

i used fetch function to make dynamic selection from my database user. When i click, the ajax didn't work.
Failed to load resource: the server responded with a status of 500
(Internal Server Error). How to fix it?
My Controller
class TambahController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
$user = User::where('jabatan','Captain Sales')->get();
return view('sales.tambah_aktivitas',compact('user'));
}
function fetch(Request $request)
{
$select = $request->get('select');
$value = $request->get('value');
$dependent = $request->get('dependent');
$data = DB::table('users')
->where($select, $value)
->groupBy($dependent)
->get();
$output = '<option value="" disabled selected >Pilih '.ucfirst($dependent).'</option>';
foreach($data as $row)
{
$output .= '<option value="'.$row->$dependent.'">'.$row->$dependent.'</option>';
}
echo $output;
}
}
My View
<div class="mb-4">
<label for="username">Divisi <span class="badge badge-danger">wajib</span></label>
<select name="kepada_divisi" id="nik" class="form-control dynamic" data-dependent="username" required autofocus>
<option value="1" disabled selected >Pilih Divisi</option>
#foreach($user as $iniuser)
<option value="{{$iniuser->nik}}">{{$iniuser->nik}}</option>
#endforeach
</select>
</div>
<div class="mb-4" >
<label for="username">Username</label>
<select name="kepada" id="username" class="form-control dynamic" >
<option value="" disabled selected >-------------------------</option>
</select>
</div>
My AJAX
<script type="text/javascript">
$('.dynamic').change(function(){
if($(this).val() != '')
{
var select = $(this).attr("id");
var value = $(this).val();
var dependent = $(this).data('dependent');
var _token = $('input[name="_token"]').val();
$.ajax({
url:"{{ route('tambah_aktivitas.fetch') }}",
method:"POST",
data:{select:select, value:value, _token:_token, dependent:dependent},
success:function(result)
{
$('#'+dependent).html(result);
}
})
}
});
$('#nik').change(function(){
$('#username').val('');
$('#kategori3').val('');
});
$('#kategori2').change(function(){
$('#kategori3').val('');
});
$("select").val();
</script>
My Route
Route::get('/tambah_aktivitas','Sales\TambahController#index');
Route::post('tambah_aktivitas/fetch', 'Sales\TambahController#fetch')->name('tambah_aktivitas.fetch');
enter image description here
i expect when i click nik selection, the select option show username which is same nik.
You should find a detailed description of the error in the storage/logs folder. At a first glance tho, the issue is here:
$user = User::where('jabatan','Captain Sales')->get();
actually returns a collection. I think you wanted to do this instead:
$user = User::where('jabatan','Captain Sales')->first();
or, instead of compact('user'), you could do a $user->toArray(). This way on the frontend you will actually receive an array containing your user, instead of an array containing a Illuminate\Support\Collection class.

How do I get my variable to show in my store function

This is probably a very simple thing, but for some reason I just can't figure it out. I created a function that gets the images from my vue component.
What I'm trying to do is take the images from my postImage() and have them in my store() function, so that I can save everything into the database.
The problem I'm getting is when I do that I get this error
Too few arguments to function App\Http\Controllers\Admin\CategoryController::store(), 1 passed and exactly 2 expected
I do understand that the error is telling me that only the $request was sent and not the $image. I'm not sure how to get it working. If I've left anything out please let me know
Here is my controller
public function store(Request $request, $image)
{
$category = new Category();
$input = $this->safeInput($request);
$category->fill($input);
dd($image);
$slug = $category->slug($category->title);
$category->slug = $slug;
if($request->has('active'))
{
$category->active = 1;
}else{
$category->active = 0;
}
$category_order = $category->order_number();
$category->order = $category_order;
$category->save();
}
public function postImage(Request $request)
{
if($request->hasFile('image'))
{
$names = [];
foreach($request->file('image') as $image)
{
$destinationPath = 'product_images/category/';
$filename = $image->getClientOriginalName();
$image->move($destinationPath, $filename);
array_push($names, $filename);
}
$image = json_encode($names);
return $image;
}
}
This is my vue component
<template>
<div class="container">
<div class="uploader"
#dragenter="OnDragEnter"
#dragleave="OnDragLeave"
#dragover.prevent
#drop="onDrop"
>
<div v-show="!images.length" :value="testing()">
<i class="fas fa-cloud-upload-alt"></i>
<div>OR</div>
<div class="file-input">
<label for="file">Select a file</label>
<input type="file" id="file" #change="onInputChange" multiple>
</div>
</div>
<div class="images-preview" v-show="images.length">
<div class="img-wrapper" v-for="(image, index) in images">
<img :src="image" :alt="`Image Uplaoder ${index}`">
<div class="details">
<span class="name" v-text="files[index].name"></span>
<span class="size" v-text="getFileSize(files[index].size)"></span>
</div>
<div class="btn btn-danger" #click="funDeleteFile(index)">
Remove
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
mounted() {
console.log('Component mounted.')
},
data() {
return {
isDragging: false,
//Sets the dragCount to 0
dragCount: 0,
//Makes files an array, so that we can send the files to the server
files: [],
//Makes images an array, so that we can let the user see the images
images: [],
}
},
methods: {
testing() {
console.log('This is submit images - '+this.files);
var formData = new FormData();
this.files.forEach(file => {
formData.append('image[]', file, file.name);
});
axios.post('/admin/category/post-image', formData);
},
OnDragEnter(e) {
//Prevents the default action of the browser
e.preventDefault();
// This lets the dragCount become 1, so that the image uploader changes colour
this.dragCount++;
// Changes the isDragging variable to true instead of false
this.isDragging = true;
return false;
},
OnDragLeave(e) {
//Prevents the default action of the browser
e.preventDefault();
// This lets the dragcount become 0, so that the image uploader changes to it's original colour
this.dragCount--;
// This is if the dragCount is <= 0 then the isDragging variable is false
if (this.dragCount <= 0)
this.isDragging = false;
},
onInputChange(e) {
// Grabs the files from the event
const files = e.target.files;
// Creates an array for files, so that we can loop thru it
// Send the file to the addImage method via "this.addImage(file)"
Array.from(files).forEach(file => this.addImage(file));
},
onDrop(e) {
//Prevents the default action of the browser
e.preventDefault();
//Stops the propagation into the other elements inside the one we drop and file into
e.stopPropagation();
// This is to disable the dragging of the images
this.isDragging = false;
// Grabs the files from the event
const files = e.dataTransfer.files;
// Creates an array for files, so that we can loop thru it
// Send the file to the addImage method via "this.addImage(file)"
Array.from(files).forEach(file => this.addImage(file));
},
addImage(file) {
//Checks if the file type is an image
if (!file.type.match('image.*')) {
this.$toastr.e(`${file.name} is not an image`);
return;
}
this.files.push(file);
const img = new Image(),
reader = new FileReader();
reader.onload = (e) => this.images.push(e.target.result);
reader.readAsDataURL(file);
},
}
}
</script>
my create.blade.php
#extends('layouts.admin')
#section('content')
#component('admin.components.products.category-form', [
'formUrl' => route('category.store'),
'formMethod' => 'POST',
'model' => $category,
'category_id' => $category_id,
'image' => '',
'image2' => ''
])
#endcomponent
#endsection
and my form
{{ Form::model($model, array('url' => $formUrl, 'method' => $formMethod, 'class' => 'add-form', 'files' => true)) }}
<div class="form-group">
{{ Form::label('category_id', 'Parent Category') }}
{{ Form::select('category_id', $category_id->prepend('Please Select', '0'), null, array('class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::label('title', 'Title') }}
{{ Form::text('title', null, array('class' => 'form-control')) }}
</div>
<div class="form-group">
<label>Active:</label>
{{ Form::checkbox('active', 0) }}
</div>
<div id="app" class="mb-20">
<category-image></category-image>
</div>
<div class="form-group">
{{ Form::submit('Save', array('class' => "btn btn-dark btn-lg btn-block")) }}
</div>
{{ Form::close() }}
My routes
Route::resource('admin/category', 'Admin\CategoryController');
Route::post('admin/category/post-image', 'Admin\CategoryController#postImage')->name('admin.category.post-image');
UPDATE
I've tried this to pass the image to a hidden field in my form so that I can grab it in the $request in my store function.
In my CategoryController#create
$category = new Category();
$category_list = Category::with('parentCategory')->get();
$category_id = Category::pluck('title', 'id');
// I've added this.
$image = '';
return view('admin.products.category.create', compact('category', 'category_list', 'category_id', 'image'));
in my CategoryController#postImage
//I've added this to, so that I can pass the image variable to the create.blade.php
return redirect()->route('category.create', compact('image'));
then in my create.blade.php I added
'my_image' => $my_image
and in my category-form.blade.php component I added
<div id="app" class="mb-20">
<category-image></category-image>
<input type="hidden" name="image" id="image" value="{{ $my_image }}">
</div>
at the moment I haven't been able to do that either. Though I'm not sure if this is the right way to go, I'm a bit worried that some random person can then add whatever they want by using the hidden input
For what do you have the parameter $image? This is not specified in your axios.post.
public function store(Request $request)
{
$category = new Category();
$input = $this->safeInput($request);
$category->fill($input);
dd($this->postImage($request));
$slug = $category->slug($category->title);
$category->slug = $slug;
if($request->has('active'))
{
$category->active = 1;
}else{
$category->active = 0;
}
$category_order = $category->order_number();
$category->order = $category_order;
$category->save();
}
public function postImage($request)
{
if($request->hasFile('image'))
{
$names = [];
foreach($request->file('image') as $image)
{
$destinationPath = 'product_images/category/';
$filename = $image->getClientOriginalName();
$image->move($destinationPath, $filename);
array_push($names, $filename);
}
$image = json_encode($names);
return $image;
}
}
If the $request is available there, Then there is no need to pass extra $image variable.
have you tried
dd($request)
or
print_r($request->toArray()); exit;
for see what's in your request!
In your create.blade you use 'formUrl' => route('category.store'), this route calls the "store" method, right? If so, it also needs to pass the $image parameter. It would be easier to identify the problem if we could se your web routes file too.
If route('category.store') does call the store method you have a few options.
1 - If you don't really need the $image parameter for the store method, you could just remove it.
2 - If you need it in a few cases, just make the parameter optional and check if it's received before handling it. Example: store(Request $request, $image = null)
3 - If this parameter actually is required, you will have to pass it everytime, even when calling routes. Example: route('category.store', ['image' => $something]). Looking at your code at this moment in create.blade you don't have the content to pass though, so I don't think this is an option.
The problem isn't the image missing in the request object sent through the form, it is the second parameter required by the category.store method.
Even if you now send the image in the form with a hidden field, you would still need to pass it as a parameter everytime you call the category.store.
Your store method is defined like
store(Request $request, $image)
So, when you call this method, even if you're just getting the route URL with route('category.store'), you do need to send the image parameter in this call.
Example:
route('category.store', ['image' => 'image id here']);
The same goes for the route definition in your web routes file. You're using a resource route, but laravel don't expect a second parameter for the store method in a default resource, so you will need to change that.
/*
adds exception to the resource so it will not handle the store method
*/
Route::resource('admin/category', 'Admin\CategoryController')->except(['store']);
//adds a custom route that supports the $image parameter.
Route::post('admin/category/{image}', 'Admin\CategoryController#store')
Now, if you're planning to send the image through the request object, you don't need it as a second parameter, so the only thing you will need to change is to make your category.store method like that.
public function store(Request $request)

Resources