How do I insert one to many relational multi data to same table in Laravel? - laravel

My table structure is:
id | parent_id | name.
My Menu model one to many relationship is:
public function childMenus() {
return $this->hasMany( ‘App\Menu’, ’parent_id’);
}
public function parentMenus() {
return $this->belongsTo(‘App\Menu’, ‘parent_id’);
}
I am creating menus with sub menus.For example I have to set 'Parent Menu' with three child menus.For this I have created a form with four inputs field.
<form>
<input type="text" name="parent">
<input type="text" name="child[]">
<input type="text" name="child[]">
<input type="text" name="child[]">
</form>
Now I want to save parent menu with its child menus at the same time.I tried to save them in array but its not working in Laravel.
Please also explain what would be the controller method for saving this data.
Thanks in advance

You can use the saveMany method to attach multiple children to a parent.
// Assuming whatever goes into the text box goes in the "name" field.
$parent = new \App\Parent();
$parent->name = \Input::get('name');
$parent->save();
$children = [];
foreach (Input::get('child') as $child) {
$children = new \App\Child([
'name' => $child
]);
}
$parent->childMenus()->saveMany($children);

I found the solution for my question.Here I am posting...
$parent_menu = $request->input('parent');
$parent = Menu::create(['name' => $parent_menu]);
$parent->save();
$child_menus = $request->input('child');
foreach($child_menus as $child_menu) {
$child = $parent->pages()->create(['name' => $child_menu]);
$child->save();
}

Related

send some variable to the blade view laravel in an addColumn () function of datatable

Its possibility of sending a variable to the blade view through the addColumn() function of datatable jquery?
I want to pass another variable to compare values ​​of the result of the query.
this is the code:
if ($request->ajax()) {
$products = Product::with('categories', 'featureds')->orderBy('name', 'ASC');
$selecteds = [];
$products_selecteds = Product::all();
foreach($products_selecteds as $products_selected){
foreach($products_selected->featureds as $featured){
array_push($selecteds, $products_selected->id);
}
}
return Datatables::of($products)->addColumn('format_price', function($product) {
return $product->format_price;
})->addColumn('checkbox', function ($product, $selecteds) {
return view('pages.products.components.table.checkbox', ['product' => $product, 'selecteds' => $selecteds]);
});
}
the array $selecteds its i want to pass to the view checkbox:
<td>
<label>
<input type="checkbox" class="checkbox-item" {{ in_array($product->id, $selecteds) ? 'checked' : "" }} value=""/>
<span></span>
</label>
</td>
Yes, it's possible to render view on additional columns. But to achieve that, you have to make the column as a Raw Column like this:
Datatable::of($products)
->addColumn('selected', function($product) use($selecteds) {
return view('product.selected', compact('product', 'selecteds'));
})
->rawColumns(['selected'])
note:
you also need to declare use keyword since $selecteds is outside the closure

How to create filter with easy way in laravel 8 using controller and checkbox

I am creating filter for the products, I tried using jquery for this before but I am not able to fix the pagination in laravel. So, I am trying this to fix the pagination as well as reduce the database query, bcoz in jquery everytime I click on any category or sub category, then it hits the database so the number of execution was more, So I replace the jquery and trying to use the button to do the same. But stuck with the array.
Can anyone help me with this?
$category = ["p1","p2","p3"];
$sub_category = ["c1","c2","c3","c4"];
$data = [];
$count = 0;
foreach ($cate as $category){
$data2 =[];
$count1 = 0;
foreach ($sub_cate as $sub){
$data2[] = [
'sub_category_id' => $category.$count1++,
'sub_category' => $sub,
'url' => $category.'|'.$sub
];
}
$data[] = [
'category_id' => 'category_'.$count++,
'category' => $category,
'sub_category' => $data2
];
}
In blade file :
#foreach($filters as $filter)
<div class="custom-control custom-checkbox mb-2">
<input type="checkbox" class="custom-control-input category_filter1" id={{$filter["category_id"]}} name="category_filter[]" value="{{$filter["category"]}}">
<label class="custom-control-label w-100" for="{{$filter["category_id"]}}">{{$filter["category"]}}</label>
#foreach($filter["sub_category"] as $sub)
<div class="custom-control custom-checkbox mb-2">
<input type="checkbox" class="custom-control-input category_filter1" id={{$sub["sub_category_id"]}} name="sub_category_filter[]" value="{{$sub["url"]}}">
<label class="custom-control-label w-100" for="{{$sub["sub_category_id"]}}">{{$sub["sub_category"]}}</label>
</div>
#endforeach
</div>
#endforeach
After using this code I am getting this type of data :
{"category_filter":["p1","p2"],"sub_category_filter":["p1|c1","p1|c2","p1|c3","p1|c1"]}
So basically the array structure is like this :
For now everything looks nice but, When I try to combine the array into once then it look some time to sort and rearrange itself, So it there any easy way to this, Each time I change the filters it will take time and then it fetch result from the database. For some reason I thought that URL which is custom made will help me but it only taking us to the wrong direction.
apply condition in conrtoller like this
if($request->input('category_filter') == "p1"){
if($request->input('sub_category_filter') == "p1|c1"){
... do your code as per your need
}
}
I share Sample Example:
assume I want to filter data like All, approved, pending, decline... then I write script in controller like this
if($request->input('filtertype')){
$filtertype = $request->input('filtertype');
if($filtertype == "All"){
$deals = Deal::orderBy('updated_at', 'desc')->get();
}else{
$deals = Deal::where('deal_isApproved', '=', $filtertype)
->orderBy('updated_at', 'desc')->get();
}
}
return view('admin.deals.index',compact('deals'));

How to redirect back to preivous template with both input and collections of Eloquent in Laravel?

I need to pass both input and collections, that this controller produce, to the previous template. I try to use:
return redirect()->back->withInput()->with('userdata',$userdata);
but get undefined variable when access $userdata in template. This is controller:
public function inquireUpdateProcess(){
$input = request()->all();
$userdata = AuthorityKind::where('authority', $input['authority'])->first();
return redirect()->back->withInput()->with('userdata',$userdata);
}
And this is template of view:
<label for="text-authority-change">name of authority:</label>
<input type="text" name="authority_name_change" class="form-control"
value="{{$userdata->authority_name}}" />
I use the following instead then it works. But the outcome is couldn't pass the input data and collection in the same time, I know there must be a way to use return redirect()->back()... and get both previous input and the collection in template.
$userdata = AuthorityKind::where('authority', $input['authority'])->first();
$binding = [
'title' => 'Authority management',
'userdata' => $userdata,
];
return view('authority.authView', $binding);
I found out the data put into with() can only get it by session in template of blade like this :
<input type="text" id="text-authority-change" name="authority_name_change" class="form-control"
value="{{session()->get('userdata')['authority_name']}}"
/>
Even the collections of Eloquent are the the same way to access.

CodeIgniter update page - Simple CRUD website assistance required

After looking through the forums and starting to try to create a basic CRUD website I am currently struggling to have a page that updates the articles as follows. If someone could kindly tell me where I am going wrong, I will be most greatful. I am getting a 404 error at 'news/input'
model (at news_model.php)
public function update($id, $data)
{
$this->db->where('id', $id);
$this->db->update('news', $data);
}
controller (news.php)
public function update($id){
$data = array(
'title' => $this->input->post('title'),
'slug' => $this->input->post('slug'),
'text' => $this->input->post('text'));
if($this->news_model->exists($id)) {
$this->news_model->update($id, $data);
}
else {
$this->news_model->insert($data);
}
}
html (views/news/input.php)
<h2>Update a news item</h2>
<?php echo validation_errors(); ?>
<?php echo form_open('news/update') ?>
<label for="title">Title</label>
<input type="input" name="title" /><br />
<label for="slug">Slug</label>
<input type="input" name="slug" /><br />
<label for="text">Text</label>
<textarea name="text"></textarea><br />
<input type="submit" name="submit" value="Update an item" />
You get a 404 because your news controller seems to have no method 'input'. Try adding something like this:
public function input(){
// load the form
$this->load->view('/news/input');
}
Note that for updating data you will need to fetch and pass it into the view first, then render the (filled out) form using set_val() and other CI functions.
Currently you're "hardcoding" the HTML form which makes populating and maintaining state (when validation fails) difficult. I suggest you play through the forms tutorial on the CI website.
Edit:
To create a update/insert (upsert) controller change as follows:
Controller:
function upsert($id = false){
$data['id'] = $id; // create a data array so that you can pass the ID into the view.
// you need to differntiate the bevaviour depending on 1st load (insert) or re-load (update):
if(isset($_POST('title'))){ // or any other means by which you can determine if data's been posted. I generally look for the value of my submit buttons
if($id){
$this->news_model->update($id, $this->input->post()); // there's post data AND an id -> it's an update
} else {
$this->news_model->insert($id, $this->input->post()); // there's post data but NO id -> it's an insert
}
} else { // nothing's been posted -> it's an initial load. If the id is set, it's an update, so we need data to populate the form, if not it's an insert and we can pass an empty array (or an array of default values)
if($id){
$data['news'] = $this->news_model->getOne($id); // this should return an array of the news item. You need to iterate through this array in the view and create the appropriate, populated HTML input fields.
} else {
$data['news'] = $this->news_model->getDefaults(); // ( or just array();) no id -> it's an insert
}
}
$this->load->view('/news/input',$data);
}
And amend the $id to the action-url in your view:
<?php echo form_open('news/upsert/'.$id) ?>

codeigniter update database with "TRUE" for checked items and "FALSE" for remaining unchecked items

I am new to php/codeignitor and trying to post changes on form checkboxes to my db. The row to modify is assigned by the gl_id below.
I am not sure how to use my update_checked function in the model to
post TRUE to each of these fields where gl_id =x and FALSE using to the remaining fields not in the array. I can create and view the array of checked values using $_POST['checked'] in the controller
and passing it to the model. Now I need to use this array to post to the db where gl_id = the value from the form in the view.
In View
<h1>Update GL id <?php echo $gl_field['gl_id'];?></h1>
<label>Stat</label>
<input type="checkbox" <?php if ($gl_field['stat'] == "TRUE") {echo "checked = checked";} ?>
name = "checked[]" id="stat" value= "stat" /><BR CLEAR="all">
<label>Exclude</label>
<input type="checkbox" <?php if ($gl_field['exclude'] == "TRUE") {echo "checked = checked";} ?>
name="checked[]" id="exclude" value= "exclude"><BR CLEAR="all">
<label>Override</label>
<input type="checkbox" <?php if ($gl_field['override'] == "TRUE") {echo "checked = checked";} ?>
name= "checked[]" id= "override" value = "override"/><BR CLEAR="all">
In Controller
public function update_table(){
$this->load->helper('form');
$this->page_nav_model->update_table();
$checked_array = $_POST['checked'];
$this->page_nav_model->update_checked($checked_array);
$this->load->view('pages/success');
}
In Model
foreach($checked_array as $true){
echo $true;
}
To clarify when I pull the information into the form in the example above all of the checkboxes are set to "TRUE" in the db so they are checked. If I uncheck stat and click submit I am able to see an array with the values (exclude, override).
I appreciate any help that sets me in the right direction.
To update your table with CI all at once, you need an array like this:
$data = array(
'column_1_name' => 'value_to_insert'
'column_2_name' => 'value_to_insert'
'column_2_name' => 'value_to_insert'
);
Right now, you have an array like this $checked_array = ('stat', 'exclude', 'override') - with more or fewer members.
To create the array that you can use in your update statement (like $data above), what you need to do is create another array with the name of each column and a value equal to 1 if it is in $checked_array or 0 if it was not in $checked array.
The function add_values() below can do that for you. You have to supply two arguments:
$all_possibilities is an array of each column name that you will want to update to either 1 or 0. In this case, it should look like $all_possibilities = array('stat', 'exclude', 'override');
$selected: this is an array with the names of the boxes that were actually selected - it is a subset of $all_possibilities (or it is the same if all the boxes were checked).
This function goes in your controller.
function add_values($all_possibilities, $selected) {
$array_for_query = array();
// this goes through each possible box that can be checked to see if that possibility was actually selected
foreach($all_possibilities as $array_member) {
// this checks to see if the current member of $all_possibilities is found in the $selected array
if (in_array($array_member, $selected)) {
// if it is, it adds that as a member of a new query $array_for_query and gives it a value of 1 (true)
$array_for_query[$array_member] = 1;
} else {
// if it is not, same as above, but gives it a value of 0
$array_for_query[$array_member] = 0;
}
}
// once all the possibilities have been checked and added to the query array, that array is returned
return $array_for_query;
}
Now you can call the function and pass the two arguments in. The returned array is assigned to $checked_and_unchecked.
$data['checked_and_unchecked'] = add_values($possibilities, $checked_array);
Make sure you also grab the gl_id from the form. You can do that with a hidden field in your view:
<input type="hidden" name="gl_id" value="<?php echo $gl_field['gl_id'];?>" />
In the controller, grab that value with
$data['gl_id'] = $this->input->post('gl_id');
Then you can pass the information to your model and update your table passing in the name of the table and the array you created.
$this->model_name->model_method($data);
This will then go in the model:
$this->db->update('table_name', $checked_and_unchecked);
$this->db->where('gl_id', $gl_id);
If a checkbox is unchecked in the HTML, the value does not get sent via $_POST. This is not accounted for in CodeIgniter. This is how I deal with this issue. In the controller:
/**
* Set post values for unchecked boxes.
*
* #access private
* #return void
*/
private function _section_checkboxes()
{
if (!$this->input->post('is_active')) {$_POST['is_active'] = 0;}
// other checkboxes here...
}
/**
* if form validation passes, run this to edit a section
*
* #access public
* #return void
*/
public function do_edit_section()
{
$this->_section_checkboxes();
if ($this->section_model->edit_section($this->input->post()))
{
redirect('success_page');
}
}
And in the model:
/**
* updates a section with active record, returns success.
*
* #access public
* #param array $data
* #return bool
*/
public function edit_section(array $data)
{
$this->db->where('id', $data['id']);
return $this->db->update('sections', $data);
}
And in the view, using the form helper:
<?=form_checkbox(array('name' => 'is_active', 'id' => 'is_active_field', 'value' => '1', 'checked' => (bool)$item->is_active))?>
Now your unchecked checkboxes are set as 0 when unchecked, 1 when checked. I hope this answers your question.
So I still needed help getting the final touches on the overall project so I wanted to post the final results here for anyone as green as I looking to control checkboxes from the db and the db from checkboxes.
Controller:
[function from Tayler and]
$all_checkbox_fields = array('stat','exclude','override');
$checked_array = $_POST['checkbox'];
$data['checkbox'] = $this->add_values($all_checkbox_fields, $checked_array);
$data['gl_id'] = $this->input->post('gl_id');
$this->page_nav_model->update_checked($data);
$this->load->view('pages/success');
Model:
public function update_checked($data){
$this->default_db->where('gl_id', $data['gl_id']);
$this->default_db->update('oracle_table', $data['checkbox']);
}
View:
<label>Stat</label>
<input type="checkbox" <?php if ($gl_field['stat'] == "1") {echo "checked = checked";} ?>
name = "checkbox[]" id="stat" value= "stat"/><BR>
<label>Exclude</label>
<input type="checkbox" <?php if ($gl_field['exclude'] == "1") {echo "checked = checked";} ?>
name="checkbox[]" id="exclude" value= "exclude"/><BR>
<label>Override</label>
<input type="checkbox" <?php if ($gl_field['override'] == "1") {echo "checked = checked";} ?>
name= "checkbox[]" id= "override" value = "override" ><BR>

Resources