Axios post method fails with status code 500 with Laravel - php

as the title says, I'm having the Axios post fail when trying to pass form data to my Laravel controller when using Vue. I've seen many people with the issue, but none of the solutions have worked for me. What I've found is that the 500 status code is a bit too vague. Digging deeper into the issue I'm having, I've found that the main issue is that I have a field in my database that can't be null, here is the error I get in laravel.log
[2018-11-07 18:45:21] development.ERROR: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'string_date' cannot be null (SQL: insert into `action_logs` (`string_date`, `user_id`, `company_name`, `name`, `communication_type`, `contact`, `status`, `action_item`, `activity_key`, `assigned_to`, `updated_at`, `created_at`) values (, 1, , , , , , , 1,2, no one, 2018-11-07 18:45:21, 2018-11-07 18:45:21)) {"userId":1,"email":"frank#*******.com","exception":"[object] (Illuminate\\Database\\QueryException(code: 23000): SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'string_date' cannot be null (SQL: insert into `action_logs` (`string_date`, `user_id`, `company_name`, `name`, `communication_type`, `contact`, `status`, `action_item`, `activity_key`, `assigned_to`, `updated_at`, `created_at`) values (, 1, , , , , , , 1,2, no one, 2018-11-07 18:45:21, 2018-11-07 18:45:21))
This seems to be showing that the data from the form isn't being passed at all, or the controller can't access the data for some reason. I'm not totally sure why though, I built this following an example that worked for me before. I tried a suggestion I saw that by default Axios sends a JSON object. I tried parsing accordingly in the Laravel controller, but that did not fix the issue. I've checked to make sure the csrf token was working properly, and it is. I was able to log a message from the controller, so I know that Vue is finding the route okay. I'm, however, calling my route trying to pass in the company name, like so:
Route::post('/action-log/{url}', 'ActionLogController#store');
I have not tried removing this yet, but that's only because I can see that it was still calling the store method as expected. Here is the relevant code from my Vue component:
<template>
<div class="table-responsive">
<table class="table table-striped table-sm">
<thead>
<tr>
<th><a id="sortby-date" class="action-nav" href="?sortby=date&sortdirection=desc">Date</a></th>
<th><a id="sortby-company" class="action-nav" href="?sortby=company&sortdirection=desc">Company</a></th>
<th><a id="sortby-name" class="action-nav" href="?sortby=name&sortdirection=desc">Name</a></th>
<th><a id="sortby-communication-type" class="action-nav" href="?sortby=communication-type&sortdirection=desc">Communication Type</a></th>
<th><a id="sortby-contact" class="action-nav" href="?sortby=contact&sortdirection=desc">Contact</a></th>
<th><a id="sortby-subject" class="action-nav" href="?sortby=subject&sortdirection=desc">Subject</a></th>
<th><a id="sortby-action" class="action-nav" href="?sortby=action&sortdirection=desc">Comment/Action Item</a></th>
<th>Archive</th>
<!-- check if admin?? -->
<th><a id="sortby-assigned-to" class="action-nav" href="?sortby=date&sortdirection=desc">Assigned To</a></th>
<!-- /check if admin?? -->
</tr>
</thead>
<tbody v-if="actions.length > 0">
<tr v-for="action in actions" :key="action.id">
<td>
{{ action.string_date }}
</td>
<td>
{{ action.company_name }}
</td>
<td>
{{ action.name }}
</td>
<td>
{{ action.communication_type }}
</td>
<td>
{{ action.contact }}
</td>
<td>
{{ action.status }}
</td>
<td>
{{ action.action_item }}
</td>
<td>
<input type="checkbox" :id="'archive-' + action.id" class="archive" :name="'archive-' + action.id">
</td>
<td :id="'record-' + action.id" class="assigned-to">
{{ action.assigned_to }}
</td>
</tr>
</tbody>
</table>
<!-- Button trigger modal -->
<p id="add-action" style="text-align: center;">
<button id="action-log-modal" type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#addAction">
Add New Action Log
</button>
</p>
<!-- Modal -->
<div class="modal fade" id="addAction" tabindex="-1" role="dialog" aria-labelledby="addActionTitle" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<form id="action-log-form" class="" name="action-log-form" role="form" method="post" :action="this.url" enctype="multipart/form-data">
<div class="modal-content">
<input type="hidden" name="_token" :value="csrf">
<div class="modal-header">
<h5 class="modal-title" id="addActionTitle">Add Action Log</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<!-- Errors -->
<div class="alert alert-danger" v-if="createAction.errors.length > 0">
<p>
<strong>Whoops!</strong> Something went wrong.
</p>
<p></p>
<ul>
<li v-for="error in createAction.errors">
{{ error }}
</li>
</ul>
</div>
<div class="form-group">
<label for="date">Date</label>
<input id="date" class="form-control form-control-sm" name="date" type="text" value="01/01/1970" placeholder="MM/DD/YYYY" required>
</div>
<div class="form-group">
<label for="company">Company</label>
<input type="text" id="company" class="form-control" name="company" :value="this.companyName" :placeholder="this.companyName" #keyup.enter="store" required readonly>
</div>
<div class="form-group">
<label for="name">Name</label>
<input type="text" id="name" class="form-control" name="name" :value="this.userFullName" :placeholder="this.userFullName" #keyup.enter="store" required readonly>
</div>
<div class="form-group">
<label for="communication-type">Communication Type</label>
<select id="communication-type" name="communication_type" class="custom-select mr-sm-2" #change="store" v-model="actions.communication_type">
<option value="not-selected">Choose...</option>
<option value="phone">Phone</option>
<option value="email" selected>Email</option>
<option value="in-person">In Person</option>
<option value="fax">Fax</option>
<option value="customer-site">Customer Site</option>
</select>
</div>
<div class="form-group">
<label for="contact">Contact</label>
<input type="text" id="contact" class="form-control form-control-sm" name="contact" value="test contact" #keyup.enter="store" v-model="actions.contact" required>
</div>
<div class="form-group">
<label for="current-status">Current Status</label>
<input type="text" id="current-status" class="form-control form-control-sm" name="current_status" value="test current status" #keyup.enter="store" v-model="actions.current_status" required>
</div>
<div class="form-group">
<label for="action-item">Action</label>
<textarea id="action-item" class="form-control" name="action_item" rows="3" #keyup.enter="store" v-model="actions.action_item">test action</textarea>
</div>
<div class="form-group">
<label>Product Document</label>
<div class="custom-file">
<input type="file" id="productDocument" class="custom-file-input" name="product_document">
<label class="custom-file-label" for="productDocument">Choose file</label>
</div>
</div>
<div class="form-group">
<label>Test Data</label>
<div class="custom-file">
<input type="file" id="testData" class="custom-file-input" name="test_data">
<label class="custom-file-label" for="testData">Choose file</label>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" #click="store">Save</button>
</div>
</div>
</form>
</div>
</div>
</div>
</template>
<script>
export default {
props: ['companyName', 'userFullName'],
data() {
return {
actions: [],
csrf: document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
createAction: {
errors: [],
date: '',
company: '',
name: '',
communication_type: '',
contact: '',
current_status: '',
action_item: ''
},
url: ''
}
},
mounted() {
// console.log('Action Log Mounted.');
this.getActions();
// updates the date when changed in add new action form
$('#date').on('changeDate', () => { this.actions.date = $('#date').val() });
},
methods: {
getActions() {
//get company name to pass to request
var currentLocation = window.location.href;
// console.log(currentLocation);
var companyName = currentLocation.split('/');
companyName = companyName[companyName.length - 1];
let url = '/action-log/' + companyName;
this.url = url;
// console.log("just stored this.url with " + this.url);
//get actions
axios.get(url)
.then(response => {
this.actions = response.data;
this.actions.company = this.companyName;
this.actions.name = this.userFullName;
})
.catch(error => {
console.log(error);
});
},
store() {
let url = window.location.href;
url = url.replace('home', 'action-logs');
console.log(this.url);
this.persistAction(
'post',
// '/' + this.url,
this.url,
this.actions,
'#addAction'
);
},
persistAction(method, uri, form, modal) {
// console.log("method = " + method);
// console.log("uri = " + uri);
// console.log("form = " + form);
// console.log("modal = " + modal);
console.log("date = " + form.date);
console.log("company = " + form.company);
console.log("name = " + form.name);
console.log("contact = " + form.contact);
console.log("current_status = " + form.current_status);
console.log("action_item = " + form.action_item);
form.errors = [];
axios[method](uri, form)
.then(response => {
this.getActions();
// console.log('seemingly successful');
form.date = '';
form.company = '';
form.name = '';
form.communicationType = 'not-selected';
form.contact = '';
form.currentStatus = '';
form.actionItem = '';
form.productDocument = '';
form.testData = '';
form.errors = [];
})
.catch(error => {
if (typeof error.response.data === 'object') {
form.errors = _.flatten(_.toArray(error.response.data));
}
else {
form.errors = ['Something went wrong. Please try again.'];
}
console.log('there was an error: ' + error);
});
}
}
}
</script>
And the code I'm trying to use from my controller:
public function store(Request $request)
{
// get company being viewed
$companyViewing = explode('/', $request->path());
$companyViewing = $companyViewing[count($companyViewing) - 1];
$data = $request->json()->all();
// Log::debug($request);
// Log::debug($data);
$action = new ActionLog();
$action->string_date = $request->date;
$action->user_id = Auth::user()->id;
$action->company_name = $request->company;
$action->name = $request->name;
$action->communication_type = $request->communication_type;
$action->contact = $request->contact;
$action->status = $request->current_status;
$action->action_item = $request->action_item;
$client_id = Company::where('name', '=', $companyViewing)->first(['id']);
$action->activity_key = '1,' . $client_id->id;
if($request->assigned_to !== null) {
$action->assigned_to = $request->assigned_to;
}
else {
$action->assigned_to = "no one";
}
$action->save();
$actions = '';
if(Auth::user()->role == 'admin') {
$actions = ActionLog::where('user_id', '=', Auth::user()->id)
->where('activity_key', '=', '1,' . $client_id->id) //return only relevant activities between AST and client, even if the client is AST!
->orderBy('created_at', 'desc')
->get();
}
else {
$actions = ActionLog::where('user_id', '=', Auth::user()->id)
->where('activity_key', '=', '1,' . $client_id->id)
->orderBy('created_at', 'desc')
->get(['id', 'string_date', 'company_name', 'name', 'communication_type', 'contact', 'status', 'action_item']);
}
return response()->json(['success' => 'Data is successfully added', 'actions' => $actions, 'role' => Auth::user()->role]);
}
EDIT: Here is the output for when I call console.log for the form data from vue.
date = 01/01/1970 app.js:47573:13
company = AST app.js:47574:13
name = Frank app.js:47575:13
contact = zxcv app.js:47576:13
current_status = test app.js:47577:13
action_item = asdf app.js:47578:13
there was an error: Error: Request failed with status code 500
Output in laravel.log when I call Log::debug($request->all()) and Log::debug($data). Both calls give this same array of information, which actually is not relevant to what I'm posting. These are the current records that already exist in the database table, which seems strange since I'm trying to get the data from the form.
[2018-11-07 19:50:14] development.DEBUG: array (
0 =>
array (
'id' => 4,
'user_id' => 1,
'company_name' => 'AST',
'name' => 'Frank',
'communication_type' => 'email',
'contact' => 'asdf',
'status' => 'fdas',
'action_item' => 'asdf',
'assigned_to' => 'no one',
'string_date' => '11/11/2018',
),
1 =>
array (
'id' => 3,
'user_id' => 1,
'company_name' => 'AST',
'name' => 'Frank',
'communication_type' => 'email',
'contact' => 'fdas',
'status' => 'fda',
'action_item' => 'fdas',
'assigned_to' => 'no one',
'string_date' => '10/24/2018',
),
2 =>
array (
'id' => 2,
'user_id' => 1,
'company_name' => 'AST',
'name' => 'Frank',
'communication_type' => 'fax',
'contact' => 'asdf',
'status' => 'asdf',
'action_item' => 'asdf',
'assigned_to' => 'rob',
'string_date' => '10/10/2018',
),
3 =>
array (
'id' => 1,
'user_id' => 1,
'company_name' => 'AST',
'name' => 'Frank',
'communication_type' => 'in-person',
'contact' => 'asdf',
'status' => 'asdf',
'action_item' => 'asdf',
'assigned_to' => 'bob',
'string_date' => '10/02/2018',
),
)
Thank you in advanced for any insight and help!

Thanks to the help of #rickdenhaan and #adam, I found that my output in the controller showed data from my database. While it seems like that there are quite a few reasons you might get a 500 response from an Axios call, my case was that I was passing the incorrect array to the call with data that didn't have anything to do with my form data and I also was binding the data in the form to the incorrect array.

Related

How do I update records in a loop in Laravel 8

I am developing a student portal in Laravel 8. I would love to update the class subjects.
Here is my controller
public function UpdateAssignSubject(Request $request, $class_id)
{
if ($request->subject_id == null) {
$notification = [
'message' => 'Sorry You did not Select any Subject',
'alert-type' => 'error'
];
return redirect()->route('assign.subject.edit', $class_id)->with($notification);
} else {
$countClass = count($request->subject_id);
AssignSubject::where('class_id', $class_id)->delete();
for ($i = 0; $i < $countClass; $i++) {
$assign_subject = new AssignSubject();
$assign_subject->class_id = $request->class_id;
$assign_subject->subject_id = $request->subject_id[$i];
$assign_subject->full_mark = $request->full_mark[$i];
$assign_subject->pass_mark = $request->pass_mark[$i];
$assign_subject->subjective_mark = $request->subjective_mark[$i];
$assign_subject->save();
} // End For Loop
}// end Else
$notification = [
'message' => 'Assigned Subject Updated Successfully',
'alert-type' => 'success'
];
}
This very piece of code AssignSubject::where('class_id', $class_id)->delete(); is giving me issues since I am using the AssignSubject as a pivot table thus deleting the Id's produces errors in the long run.
Here is my view
#foreach($subjects as $subject)
<option value="{{ $subject->id }}" {{ ($edit->subject_id == $subject->id)? "selected": ""
}}>{{ $subject->name }}</option>
#endforeach
<div class="form-group">
<h5 style="color:black">Full Mark <span class="text-danger">*</span></h5>
<div class="controls">
<input type="text" name="full_mark[]" value="{{ $edit->full_mark }}" class="form-control"
style="background-color: rgb(176, 172, 216);color:black" >
</div>
<div class="col-md-2">
<div class="form-group">
<h5 style="color:black">Pass Mark <span class="text-danger">*</span></h5>
<div class="controls">
<input type="text" name="pass_mark[]" value="{{ $edit->pass_mark }}" class="form-control"
style="background-color: rgb(176, 172, 216);color:black">
</div>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<h5 style="color:black">Subjective Mark <span class="text-danger">*</span></h5>
<div class="controls">
<input type="text" name="subjective_mark[]" value="{{ $edit->subjective_mark }}" class="form-
control" style="background-color: rgb(176, 172, 216);color:black">
</div>
</div>
</div>
Please how can I update the record without deleting first. Any help would be greatly appreciated.
Instead of deleting all entities, you can simply update them if they do exist.
In case they do not, you need to create a new one, like you did in your for loop.
I adjusted your code, to check if a subject already exists, if it does it updates it, otherwise a new one is created
$countClass = count($request->subject_id);
// remove this line
// AssignSubject::where('class_id', $class_id)->delete();
for ($i = 0; $i < $countClass; $i++) {
// a class can only have each subject 1 time, so you can filter for it
$entity = AssignSubject::where('class_id', $class_id)
->where('subject_id', $request->subject_id[$i])
->first();
// if entry does not exist, ->first() will return null, in this case, create a new entity
$assign_subject = $entity ?? new AssignSubject();
// update columns
$assign_subject->class_id = $request->class_id;
$assign_subject->subject_id = $request->subject_id[$i];
$assign_subject->full_mark = $request->full_mark[$i];
$assign_subject->pass_mark = $request->pass_mark[$i];
$assign_subject->subjective_mark = $request->subjective_mark[$i];
// save changes
$assign_subject->save();
}

form input cleared after submit data using laravel fram work

I have multiple data base connection when I validate name of product I send message product name is exist before to view and here problem is appeared.
Message appeared in view but all form inputs is cleared.
How I recover this problem taking in consideration if product name not exist. validation executing correctly and if found error in validation it appeared normally and form input not cleared.
this my controller code.
public function add(Request $request)
{
// start add
if($request->isMethod('post'))
{
if(isset($_POST['add']))
{
// start validatio array
$validationarray=$this->validate($request,[
//'name' =>'required|max:25|min:1|unique:mysql2.products,name|alpha',
'name' =>'required|alpha',
'price' =>'required|numeric',
]);
// check name is exist
$query = dBHelper::isExist('mysql2','products','`status`=? AND `deleted` =? AND `name`=?',array(1,1,$validationarray['name']));
if(!$query) {
$product=new productModel();
// start add
$product->name = $request->input('name');
$product->save();
$add = $product->id;
$poducten = new productEnModel();
$poducten->id_product = $add;
$poducten->name = $request->input('name');
$poducten->price = $request->input('price');
$poducten->save();
$dataview['message'] = 'data addes';
} else {
$dataview['message'] = 'name is exist before';
}
}
}
$dataview['pagetitle']="add product geka";
return view('productss.add',$dataview);
}
this is my view
#extends('layout.header')
#section('content')
#if(isset($message))
{{$message}}
#endif
#if(count($errors)>0)
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
#endif
<form role="form" action="add" method="post" enctype="multipart/form-data">
{{csrf_field()}}
<div class="box-body">
<div class="form-group{{$errors->has('name')?'has-error':''}}">
<label for="exampleInputEmail1">Employee Name</label>
<input type="text" name="name" value="{{Request::old('name')}}" class="form-control" id="" placeholder="Enter Employee Name">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email Address</label>
<input type="text" name="price" value="{{Request::old('price')}}" class="form-control" id="" placeholder="Enter Employee Email Address">
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="add" class="btn btn-primary">Add</button>
</div>
</form>
#endsection
this is my route
Route::get('/products/add',"produtController#add");
Route::post('/products/add',"produtController#add");
You can create your own custom validate function like below. I guess this should help you.
Found it from https://laravel.com/docs/5.8/validation#custom-validation-rules -> Using Closures
$validationarray = $this->validate($request,
[
'name' => [
'required',
'alpha',
function ($attribute, $value, $fail) {
//$attribute->input name, $value for that value.
//or your own way to collect data. then check.
//make your own condition.
if(true !=dBHelper::isExist('mysql2','products','`status`=? AND `deleted` =? AND `name`=?',array(1,1,$value))) {
$fail($attribute.' is failed custom rule. There have these named product.');
}
},
],
'price' => [
'required',
'numeric',
]
]);
First way you can throw validation exception manually. Here you can find out how can you figure out.
Second way (I recommend this one) you can generate a custom validation rule. By the way your controller method will be cleaner.

Laravel trying to add to database

I'm new on Laravel framework. I'm trying to save from forms to database.
Example:
Input STEAM_ID:
Input Access:
Controller:
public function admins_add()
{
$serveradmins = DB::table('server_admins')->first();
$this->title('Add admins');
$this->pageView('servers::admins_add', ['serveradmins' => $serveradmins]);
DB::table('server_admins')->insert(
array(
$serveradmins->auth = Input::get('steam-id'),
$serveradmins->access = Input::get('access'),
$serveradmins->password = 'nopass',
$serveradmins->flags = 'ce',
$serveradmins->added_by = Input::get('added_by')
)
);
$serveradmins->save();
return Redirect::back();
}
Views:
<div class="page page-servers page-servers-admin-form">
<form method="POST" action="/admin/servers/admins/create" accept-charset="UTF-8" class="form-horizontal">
<div class="form-group ">
<label for="title" class="col-sm-3 control-label">STEAM ID</label>
<div class="col-sm-9">
<input name="steam-id" type="text" id="steam-id">
</div>
</div>
<div class="form-group ">
<label for="access" class="col-sm-3 control-label">Teisės</label>
<div class="col-sm-9">
<input name="access" type="hidden" value="" id="access">
<select id="access" name="access"><option value="" selected="selected">-</option>
<option value="abcdefghijklmnopqrstuv">Owner</option>
<option value="bcdfijmnopqruv">Admin</option>
<option value="3" disabled>PREMIUM</option>
</select>
</div>
</div>
<div class="form-actions">
<button type="submit" name="_form_submit" class="btn btn-default" value="1">
<i class="fas fa-save "></i>
SAVE!
</button>
<button type="button" onclick="document.location.href='/admin/servers/admins'" class="btn btn-default">
<i class="fas fa-times "></i> Cancel
</button>
</div>
</form>
</div>
</section>
And my routes:
ModuleRoute::get('admin/servers/admins/create', 'AdminServersController#admins_add');
ModuleRoute::post('admin/servers/admins/create', 'AdminServersController#admins_add');
Dont be mad on my if my code is terrible, i'm new on laravel and really like it! Thanks guys for helping :)
First: Why do you want to execute admins_add() in your get route? Create a function called index() for easier understanding and tell that function to return the view like
public function index() {
$serveradmins = DB::table('server_admins')->first();
return view('viewname')->with('serveradmins', $serveradmins);
}
Then your admins_add()should look like this:
public function admins_add(Request $request)
{
ServerAdmin::create([
'auth' => $request->steam-id,
'access' => $request->access,
'password' => 'nopass',
'flags' => 'ce',
'added_by' => $request->added_by
]);
return Redirect::back();
}
And before executing generate the ServerAdmin Model via CLI ( php artisan make:model ServerAdmin) and inside this model you change the fillables to
protected $fillable = [
'auth',
'access',
'password',
'flags',
'added_by'
];
and set
protected $table = 'server_admins';
Edit: As N Mahurin mentioned in the comments - take this solution for practicing with Laravel. Mass Assignments have a heavy security risk. Read here about it:
https://laravel.com/docs/5.6/eloquent#mass-assignment
Your insert is off. It should be key => value pairs (where the key is the column name in the DB). Try
DB::table('server_admins')->insert([
'auth' => Input::get('steam-id'),
'access' => Input::get('access'),
'password' => 'nopass',
'flags' => 'ce',
'added_by' => Input::get('added_by')
]);
See https://laravel.com/docs/5.6/queries#inserts for more info. You can also go the eloquent route and do:
$serverAdmin = new ServerAdmin();
$serverAdmin->auth = Input::get('steam-id'),
$serverAdmin->access = Input::get('access'),
$serverAdmin->password = 'nopass',
$serverAdmin->flags = 'ce',
$serverAdmin->added_by = Input::get('added_by')
$serverAdmin->save();

get checked option value in laravel

I have input group include 2 options checkbox and input field.
I want to get value of input field only if checkbox is checked
otherwise ignore that input field.
Codes
#foreach($list as $columns)
<div class="input-group">
<span class="input-group-addon">
<input type="checkbox" checked="checked">
</span>
<input type="text" name="{{$columns}}" value="{{$columns}}" class="form-control">
</div><!-- /input-group -->
#endforeach
currently I get all my inputs in my controller regardless they are checked or not:
$column = $request->except('_token');
How do I pass this to my controller function?
UPDATE
as requested : my code $list dd is:
array:27 [▼
0 => "id"
1 => "title"
2 => "slug"
3 => "imageOne"
4 => "imageTwo"
5 => "short_description"
6 => "description"
7 => "price"
8 => "meta_description"
9 => "meta_tags"
10 => "arrivalDays"
11 => "height"
12 => "weight"
13 => "lenght"
14 => "width"
15 => "sku"
16 => "stock"
17 => "label"
18 => "label_from"
19 => "label_to"
20 => "label_color"
21 => "status_id"
22 => "brand_id"
23 => "category_id"
24 => "subcategory_id"
25 => "created_at"
26 => "updated_at"
]
UPDATE 2
To be clear how it works exactly i included screenshot
SEE IT
1) change the name of checkbox to cb[] and input to input[]
#php
$no = 0;
#endphp
#foreach($list as $columns)
#php
$no+=1;
#endphp
<div class="input-group">
<span class="input-group-addon">
<input type="checkbox" name="cb[{{$no}}]" checked="checked">
</span>
<input type="text" name="input[{{$no}}]" value="{{$columns}}" class="form-control">
</div><!-- /input-group -->
#endforeach
2)filter your $request and include just the checked checkbox
$input = $request->except('_token');
foreach ($input['cb'] as $key => $value) {
if ($value== 'on') {
$getRealInput[$key] = $input['input'][$key];
}
}
return $getRealInput;
Try This:
1) first of all mention checkbox name like this :
#foreach($list as $columns)
<div class="input-group">
<span class="input-group-addon">
<input name="checkbox" type="checkbox" checked="checked">
</span>
<input type="text" name="{{$columns}}" value="{{$columns}}" class="form-control">
</div><!-- /input-group -->
#endforeach
2) In Controller try this:
$inputs = asset($request->checkbox) && $request->checkbox !='' ? $request->except('_token') : []; //if you want to remove input fields use unset inputs instead of []
dd($inputs)
You could name the checkbox as an array
#foreach($list as $columns)
<div class="input-group">
<span class="input-group-addon">
<input type="checkbox" name="cb[]" value="{{ $columns }}">
</span>
<input type="text" name="{{$columns}}" value="{{$columns}}" class="form-control">
</div><!-- /input-group -->
#endforeach
and in your controller you could get the checked items as
foreach ($request->cb as $checked) {
$request->{$checked} // The textbox corresponding to the selected checkbox
}
You should try this:
Updated Answer:
#foreach($list as $columns)
<div class="input-group">
<span class="input-group-addon">
<input type="checkbox" name="columns[]" value="{{ $columns }}">
</span>
<input type="text" name="{{$columns}}" value="{{$columns}}" class="form-control">
</div><!-- /input-group -->
#endforeach
In controller :
$columns = $request->columns;
print_r($columns);
First of all, identify each checkboxes with unique names(use columns[]).
Here I guess you don't expect manual entry(modification) as you populate the value of $columns in your text input field. If so, yoou could use a label instead:
#foreach($list as $key => $columns)
<div class="input-group">
<span class="input-group-addon">
<input name="columns[]" type="checkbox" value={{$key}} checked="checked">
</span>
<label class="form-control">{{$columns}}</label>
</div>
#endforeach
UPDATE:
VIEW
#foreach($list as $key => $columns)
<span class="input-group-addon">
<input name="col_keys[]" type="checkbox" value={{$key}} checked="checked">
</span>
<input type="text" name="col_texts[]" value="{{$columns}}" class="form-control">
#endforeach
CONTROLLER
Now $request->col_keys will have an array of keys that are valid for $request->col_texts. So do a sorting:
$valid_keys = $request->col_keys;
$all_texts = $reqest->col_texts;
foreach($all_texts as $key => $item) {
if (($key = array_search($key, $valid_keys)) === false) {
unset($all_texts($key));
}
}
SOLVED
First of all I have to thank everyone who tried to help me solve this issue specially Wahyu Fadzar. Here is how I solved my issue:
I changed my blade code to:
#php $no = 0; #endphp //Wahyu Fadzar idea
#foreach($list as $columns)
#php $no+=1; #endphp //Wahyu Fadzar idea
<div class="input-group">
<span class="input-group-addon">
<input type="checkbox" name="cb[{{$no}}]" checked="checked"> //Wahyu Fadzar idea
</span>
<input type="text" name="customname[{{$no}}]" value="{{$columns}}" //Wahyu Fadzar ideaclass="form-control">
<input type="hidden" name="defaultname[{{$no}}]" value="{{$columns}}"> // Added
</div><!-- /input-group -->
#endforeach
Controller
public function export(Request $request) {
// defaultname that i added in my blade used here (explaination below)
$input = $request->except('_token');
foreach ($input['cb'] as $key => $value) {
if ($value== 'on') {
$getRealInput[$key] = $input['defaultname'][$key];
}
}
$products = Product::select($getRealInput)->get(); //getting table selected columns
Excel::create('products', function($excel) use($products, $request) {
$excel->sheet('sheet 1', function($sheet) use($products, $request){
//Wahyu Fadzar code used here to get selected columns data
$input = $request->except('_token');
foreach ($input['cb'] as $key => $value) {
if ($value== 'on') {
$getCustomInput[$key] = $input['customname'][$key];
}
}
$sheet->fromArray($products, null, 'A1', false, false);
$sheet->row(1, $getCustomInput);
});
})->export('csv');
return redirect()->back();
}
Explanations
I had issue before when I used Wahyu code it would remove my inputs from CSV file as i unchecked them, but their data still exist in my file
so I added
< input type = " hidden " name = " defaultname[{{$no}}] " value = " {{$columns}} " >
and by this i will get my default column names even if i edit it for export. otherwise it would return error, eg. I changed my title column to name it says there is no column name! so by this my title column will stay title for select query.
I used it in:
$products = Product::select($getRealInput)->get();
I used Wahyu code in my export part in order to get custom input names for my CSV file and not the default ones.
< input type = " text " name = " customname[{{$no}}] " value = "
{{$columns}} " class = " form-control " >
goes to:
if ($value== 'on') {
$getCustomInput[$key] = $input['customname'][$key];
}
inside my export query.
Hope it help others as well.
THANK YOU ALL.

how to fix preg_replace():Parameter mismatch, pattern is a string while replacement is an array

I am getting the check box values(multiple values) from view where user select the topics they are interested and store multiple values in a column in my database. So used serialize() to store them in my database. When i try to do that. It throws me the above mentioned error. I went through previous questions in Stackoverflow and did few changes like
$data = array(
'topics' => $post['topics'] ,);
to
$data = [
'topics' => $post['topics'] ,];
Again it shows the same error , Here is my View
<div class="panel-body">
<center><h2> Select the topic you are interested in</h2></center><br>
<form enctype="multipart/formdata"class="form-horizontal" role="form" method="POST" action="{{ url('/topicStore') }}">
{{ csrf_field() }}
<center>
<input type="checkbox" name="topics[]" value="sports"> Sports</input>
<input type="checkbox" name="topics[]" value="education"> Education</input>
<input type="checkbox" name="topics[]" value="family"> Family</input>
<input type="checkbox" name="topics[]" value="friends"> Friends</input></center><br>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
<i class="fa fa-btn fa-user"></i>Add topics
</button>
</div>
</div>
</div>
Here is my controller.
public function storeSelection(Request $request)
{
$post = $request->all();
$val=\Validator::make($request->all(),
[
'topics' => 'required',
]);
if ($val ->fails())
{
return redirect()->back()->withErrors($val->errors());
}
else
{
$data = array(
'topics' => $post['topics'] ,
);
$topics = serialize($data);
$updatedata = DB::table('users')->where('name',\Auth::user()->name)
->update($data);
if ($updatedata>0) {
return redirect('home');
}
}
}
I want to save the array of data which i get from the view to a column in database. I have used serialize(). Are there any other better ways to do this ?

Categories