How to show many to many values in view table without duplicate - laravel

Hello i am doing a panel where a client can select one or multiple products and make an order. I have made the table connection for many to many.
This is the migration code for ordering table:
public function up()
{
Schema::create('orders', function (Blueprint $table)
{
$table->id();
$table->string('order_number')->nullable();
$table->unsignedBigInteger('client')->nullable();
$table->unsignedBigInteger('products')->nullable();
$table->string('amount')->nullable();
$table->string('description')->nullable();
$table->timestamps();
$table->foreign('client')->references('id')->on('clients')->onDelete('cascade');
$table->foreign('products')->references('id')->on('products')->onDelete('cascade');
});
}
This is the store method that i have made in the OrderController :
public function store(Request $request)
{
$request->validate([
'order_number' => 'required',
'client' => 'required',
'products' => 'required',
'amount' => 'required',
'description' => 'required',
]);
for($i = 0; $i < count($request->products); $i++)
{
$values[] = [
'order_number' => $request->order_number,
'client' => $request->client,
'products' => $request->products[$i],
'amount' => $request->amount[$i],
'description' => $request->description,
];
$amount = Product::findorFail($request->products[$i]);
$total_value = $request->amount[$i] + $amount->amount;
$amount->update(['amount'=>$total_value]);
}
Order::upsert($values,'order_number');
return redirect('/')->with('msg', 'Order Saved successfully!');
}
If i make dd i will have an array.
This is an image how the table order looks like after one user has made one order with many products selected:
Now i want to have a table where i can show the results from the database and it looks like this:
Is it possible to make it show only one row without duplicating 3 times?
This is the code of this view:
#extends('layouts.app')
#section('content')
<div class="wrapper-index">
<h1>Total Products</h1>
<table class="table table-striped">
<tr>
<th>Order Number</th>
<th>Client</th>
<th>Description</th>
<th>Edit</th>
<th>Delete</th>
</tr>
#foreach($orders as $order)
<tr>
<td> {{$order->order_number}} </td>
<td> {{$order->client}} </td>
<td> {{$order->description}} </td>
<td>
<a href="{{route('orders.show',$order->id)}}">
<button>Edit</button>
</a>
</td>
<td>
<form action="{{route('orders.destroy',$order->id)}}" method="POST">
#csrf
#method('DELETE')
<button>Delete</button>
</form>
</td>
</tr>
#endforeach
</table>
<p class="msg">{{session('msg')}}</p>
</div>
#endsection

Here is the solution,
It's simple..
You have many-to-many relationship between products and the orders tables.
You can get unique data by using groupBy() method.
group the products with order_id(order_number).
Get the order details by database like this way and return the data to your blade file,
public function index()
{
$orders = Order::with('client','products')->groupBy('order_number')->get();
return view('orders.index', compact('orders'));
}
Hope you will fix this issue...

Related

How to pass data collection to mail in Laravel?

How to pass data collection to mail? I don't know the proper term but set of data I guess. I want to display a list of users in my pdf. Every time I use foreach in blade, it fails to send the mail. Ex. I want to display the users John Doe, Jane Doe, Peter Parker from model Signature to my pdf mail. my reference for sending mail with pdf.
In my controller
public function sendEmail(Request $request)
{
$sig = Signature::all();
$users = StudentApplicant::whereIn("id", $request->ids)->get();
foreach ($users as $key => $user) {
$data = [
'studnum' => $user->users->stud_num,
'fname' => $user->users->first_name,
'mname' => $user->users->middle_name,
'lname' => $user->users->last_name,
'gwa' => $user->gwa,
'award' => $user->award_applied,
'award_name' => $user->award->name,
'sy' => $user->school_year
];
$details = ['email' => $user->users->email];
SendEmailJob::dispatch($details, $data, $data['studnum'], $sig);
}
StudentApplicant::whereIn("id", $request->ids)->update(['certificate_status' => 1]);
return response()->json(['success' => 'Send email successfully. Refresh the page']);
}
cert blade file
<table class="table2">
<tr>
#foreach ($sig->take(3) as $item)
<td width="21%">
<b>{{ $item->name }}</b><br>
{{ $item->position }}
</td>
#endforeach
</tr>
</table>
<table class="table2">
<tr>
#foreach ($sig as $item)
#if ($loop->last)
<td>
<b>{{ $item->name }}</b><br>
{{ $item->position }}
</td>
#endif
#endforeach
</tr>
</table>

My form is not submitting what can i do there is 1 field named "done_at" is optional

This is my TaskController where done_at is optional and their is relation with 1 model named Staff.
public function create()
{
$staffs = Staff::all();
return view('tasks.create', compact('staffs'));
}
public function store(Request $request)
{
$request->validate([
'staff_id' => 'required',
'task' => 'required',
'done_at' => 'sometimes',
]);
$task = Task::create([
'staff_id' => $request->input('staff_id'),
'task' => $request->input('task'),
'done_at' => $request->input('done_at'),
]);
return redirect()->route('tasks.index')->withSuccess('Done');
}
This is my Task model where their is relationship with staff model.
use HasFactory;
protected $table = 'tasks';
protected $fillable = [
'staff_id',
'task',
];
public function staff(){
return $this->belongsTo(Staff::class);
}
This is my Staff model with has relationship with task model.
use HasFactory;
protected $table = 'staffs';
protected $fillable = [
'name',
'gender',
'date_of_birth',
];
public function task() {
return $this->hasMany(Task::class);
}
This is my tasks.create page where there is form which is not submitting the done_at field is optional.
<form method="post" action="{{route('staffs.store')}}">
#csrf
<table>
<tr>
<td>Staff Name : </td>
<td>
<select name="staff_id" id="staff_id">
<option value="">Select One</option>
#foreach ($staffs as $staff)
<option value="{{ $staff->id }}">{{ $staff->name }}</option>
#endforeach
</select>
</td>
</tr>
<tr>
<td>Task : </td>
<td><input type="text" name="task" class="form-control"></td>
</tr>
<tr>
<td>Done At :</td>
<td><input type="time" name="done_at" class="form-control"></td>
</tr>
<td><button class="btn btn-primary" name="submit" type="submit" value="submit" id="submit">Submit</button></td>
</table>
</form>
This is my tasks table and this is structure of Task.
public function up()
{
Schema::create('tasks', function (Blueprint $table) {
$table->id();
$table->bigInteger('staff_id')->nullable();
$table->string('task')->nullable();
$table->dateTime('done_at')->nullable();
$table->timestamps();
});
}
try this,
$request->validate([
'staff_id' => 'required',
'task' => 'required',
'done_at' => 'nullable',
]);
In Task Model add done_at field in fillable
protected $fillable = [
'staff_id',
'task',
'done_at'
];
what is the actual error you're getting?
You can check with this code.
public function store(Request $request)
{
$request->validate([
'staff_id' => 'required',
'task' => 'required',
'done_at' => 'sometimes',//put proper validation here. if it is optional you can remove this line.You can also use required_if:field_name or required_with:field_name
]);
}
and put done_at in your model $fillable array.

I retrieved form input in three ways in codeigniter? which one is right way

I retrieved form input in three ways in codeigniter? I am unsure which one is correct. I have given this line
$this->load->view('userview',$data);
Is this correct? What is the right way to input the data from the form? When should I use an array?
I also want to know if the record was added successfully. After submitting the form, which function would I have to use and where would I put it?
view folder file name userview.php
userview.php
<form name="f1" action="" method="post"/>
<table width="500" border="1">
<tr>
<td>UserName</td>
<td>:</td>
<td><input type="text" name="username" value=""/></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input type="password" name="password" value=""/></td>
</tr>
<tr>
<td>Email</td>
<td>:</td>
<td><input type="text" name="email" value=""/></td>
</tr>
<tr>
<td colspan="3"><input type="submit" name="submit" value="Save"/></td>
</tr>
</table>
</form>
First one-created Array and stored into variable:
public function index()
{
$data = array();
if($this->input->post('submit') != NULL ){
$postData = $this->input->post();
$data['response'] = $postData;
}
$this->load->view('userview',$data);
}
Second one: retrieved input variable within array
public function index()
{
$data['response']=array('username' => $this->input->post('username'),
'password' => $this->input->post('password'),
'email' => $this->input->post('email'));
$this->load->view('userview',$data);
}
Third one: created one method within index function
public function index()
{
$this->load->view('userview');
$this->getvalue();
}
public function getvalue()
{
if($this->input->post('submit')!==null)
{
$data['response']=array('username' => $this->input->post('username'),
'password' => $this->input->post('password'),
'email' => $this->input->post('email'));
$this->load->view('viewuser',$data);
}
}
All are OK, Personally I use the following when I have multiple fields:
$UserDetails = $this->input->post(['username', 'email', 'password']);
This would return a key => value pair array that contains the 3 fields I need only.
In your first example, you might be returning extra fields that you don't need.
Your second example is very verbose for my taste but it's OK.
3rd example is also very verbose for my taste but it's OK.
I would use form validation instead of manually checking if the form is posted.
$data = [];
$form_validation = array(
['field' => 'username', 'label' => 'Username', 'rules' => 'trim|required'],
['field' => 'email', 'label' => 'Email', 'rules' => 'trim|required|email'],
['field' => 'password', 'label' => 'Password', 'rules' => 'trim|required'],
);
$this->form_validation->set_rules($form_validation);
if ( $this->form_validation->run() === false ) {
// set some error messages here
}else{
// get data here
$data['UserDetails'] = $this->input->post(['username', 'email', 'password']);
}
// pass data to view ??
$this->load->view('view', $data)
Here you go:
Form Validation: https://www.codeigniter.com/userguide3/libraries/form_validation.html
Input Class: https://www.codeigniter.com/userguide3/libraries/input.html
Form Helper: https://www.codeigniter.com/userguide3/helpers/form_helper.html
Good luck : )

ERROR, when deleting multiple rows in codeigniter

my table name is inbox (id, date, message). and here is my code,
in view : inbox.php
<?php $attribute = array('class' => 'check', 'id' => 'myform'); ?>
<?php echo form_open('messages/remove_checked', $attribute); ?>
<table class="table table-striped table-bordered tablesorter" id="mytable">
<tr><th width="5px" class=specalt ><input type="checkbox" id="select_all" name="select_all"/></th><th>date</th><th>Message</th></tr>
<?php foreach($inbox as $row) : ?>
<tr>
<td width="5px" class=spec><input type="checkbox" name="cntact[]" class="check" value="<?php echo $row->ID; ?>"></td>
<td><? echo $row->Date; ?></td>
<td><? echo $row->Message; ?></td>
</tr>
<?php endforeach;?>
</table>
i add this one to check all the checkbox,
<script>
$(document).ready(function() {
$('#select_all').click(function() {
var c = this.checked;
$(':checkbox').prop('checked',c);
});
});
</script>
my controller : messages.php
function remove_checked()
{
//validation rules
$this->load->library('form_validation');
$this->form_validation->set_rules('cntact[]', 'Private Contact', 'required|xss_clean');
if ($this->form_validation->run() == FALSE)
{
$remove = "No <strong>Data</strong> deleted!";
$this -> json_response(FALSE, $remove);
redirect("messages/inbox");
}
else //success
{
$checked_messages = $this->input->post('cntact'); //selected messages
$this->Mysms_model->delete_checked($checked_messages);
//redirect to
redirect("messages/inbox");
}
}
and my model : Mysms_model.php
function delete_checked($cntact)
{
$this->db->where_in('ID', $cntact)
->delete('inbox');
return $this->db->affected_rows() > 0;
}
the problem is, when i run this code, i found an error.
"DELETE FROM inbox WHERE ID IN ('on', 'on')".
so, what s on? it should number of ID, any answer?
thank you.
This is not meant to be an answer to the question, however, I just wanted to show you an alternative way to write your view using codeigniters built in libraries and helpers:
<?php
$this->load->helper('form');
$this->load->library('table');
echo form_open('messages/remove_checked', array('class' => 'check', 'id' => 'myform'));
$this->table->set_template(array('table_open' => '<table class="table table-striped table-bordered tablesorter" id="mytable">'));
$this->table->set_heading(
array('width' => '5px', 'class' => 'specalt', 'data' => form_checkbox(array('id' => 'select_all', 'name' => 'select_all'))),
'date',
'message'
);
foreach ($inbox as $row) {
$this->table->add_row(
array('width' => '5px', 'class' => 'spec', 'data' => form_checkbox(array('class' => 'check', 'name' => 'cntact[]', 'value' => $row->ID))),
$row->Date,
$row->Message
);
}
echo $this->table->generate();
echo form_close();

Invalid argument supplied for foreach() in codeigniter (tiara)

i get error in the CI view page, as Invalid argument supplied for foreach().
this is my code :
my database:
(table of Penyewa)
**id_penyewa
nama_penyewa
alamat
no_telp**
(table of Jaminan)
**id_penyewa
jenis_jaminan
ket_jaminan**
in Controller (penyewa.php)
function Penyewa()
{
parent::Controller();
$this->load->database();
$this->load->model('model_tampil');
}
function tambah()
{
$ck=$this->input->post('id_penyewa');
if($ck!='')
{
$this->model_tampil->insertPenyewa();
}
$this->load->view('tampilpenyewa');
}
function sukses()
{
echo "Data berhasil di input!";
?>
<br />
Tambah Data
<br />
Lihat Data
<?php
}
in Model (model_tampil.php)
function getPenyewa(){
$this->db->select('*');
$this->db->from('penyewa');
$this->db->join('jaminan','jaminan.id_penyewa = penyewa.id_penyewa');
$q = $this->db->get();
$rows = $q->num_rows();
$q_result = $q->result();
if($rows>0){
foreach($q_result as $row){
$data[] = $row;
}
return $data;
}
}
function insertPenyewa()
{
/*$this->db->trans_start();
$this->db->query('INSERT INTO penyewa VALUES($id_penyewa, $nama_penyewa, $alamat, $no_telp, $jenis_jaminan)');
$table1_id = $this->db->insert_id();
$this->db->query('INSERT INTO jaminan VALUES(id_penyewa,' . $table1_id .',jenis_jaminan)');
$this->db->trans_complete(); */
$this->id_penyewa=$this->input->post('id_penyewa');
$this->nama_penyewa=$this->input->post('nama_penyewa');
$this->alamat=$this->input->post('alamat');
$this->no_telp=$this->input->post('no_telp');
$this->jenis_jaminan=$this->input->post('jenis_jaminan');
$this->db->insert('penyewa',$this);
redirect('penyewa/sukses');
}
in views (tampilPenyewa.php)
<center>
<h3>Tabel data Penyewa</h3>
<table border="1">
<tr align="center" bgcolor="#33CC99">
<td width="100">ID Penyewa</td>
<td width="200">Nama Penyewa</td>
<td width="120">Alamat</td>
<td width="150">Nomor Telepon</td>
<td width="150">Jenis Jaminan</td>
<td>Tindakan Lanjut</td>
</tr>
<?php foreach ($records as $row) : ?>
<tr height="35">
<td> <?php echo $row->id_penyewa; ?></td>
<td> <?php echo $row->nama_penyewa; ?></td>
<td> <?php echo $row->alamat; ?></td>
<td> <?php echo $row->no_telp; ?></td>
<td> <?php echo $row->ket_jaminan; ?></td>
<td></td>
</tr>
<?php endforeach; ?>
</table>
<br />
Tambah Data
and in views too (inputpenyewa.php)
<center>
<?php
$this->load->library('validation');
$id_penyewa=array(
'name' => 'id_penyewa',
'id' => 'id_penyewa',
'value' => '',
'maxlength' => '100',
'size' => '50',
'validation' => "required");
$nama_penyewa=array(
'name' => 'nama_penyewa',
'id' => 'nama_penyewa',
'value' => '',
'maxlength' => '100',
'size' => '50',
'validation' => "required");
$alamat=array(
'name' => 'alamat',
'id' => 'alamat',
'value' => '',
'maxlength' => '500',
'size' => '',
'validation' => "required");
$no_telp=array(
'name' => 'no_telp',
'id' => 'no_telp',
'value' => '',
'maxlength' => '100',
'size' => '50',
'validation' => "required");
$ket_jaminan=array(
'name' => 'jenis_jaminan',
'id' => 'jenis_jaminan',
'value' => '',
'maxlength' => '100',
'size' => '50',
'validation' => "required");
$this->load->helper('form');
echo validation_errors();
echo form_open('penyewa/tambah');
echo '<center><h3>Input Data Penyewa</h3></center>';
echo "<table border='0' class='tabledetail' align='center'>";
echo
"<tr>"."<td>".form_label('ID')."</td>"."<td>".form_input('id_penyewa')."</td>"."</tr>";
echo
"<tr height=50>"."<td>".form_label('Nama Penyewa')."</td>"."<td>".form_input('nama_penyewa')."</td>"."</tr>";
echo
"<tr height=220>"."<td>".form_label('Alamat')."</td>"."<td>".form_textarea('alamat')."</td>"."</tr>";
echo
"<tr>"."<td>".form_label('No Telp')."</td>"."<td>".form_input('no_telp')."</td>"."</tr>";
echo
"<tr height=220>"."<td>".form_label('Jaminan')."</td>"."<td>".form_textarea('jenis_jaminan')."</td>"."</tr>";
echo
"<tr height=50>"."<td colspan=2 align='center'>".form_submit('mysubmit','Simpan')."</td>"."</tr>";
echo "</table>";
echo form_close();
?>
Lihat Data
okay, i am sorry if my question is very much and much..
thank you :)
update:
okey, i've doing that, but nothing result, my page error again..
and, i want to ask again, any mistake in model_tampil->getPenyewa() ??
this is the script :
function getPenyewa(){
$this->db->select('*');
$this->db->from('penyewa');
$this->db->join('jaminan','jaminan.id_penyewa = penyewa.id_penyewa');
$q = $this->db->get();
$rows = $q->num_rows();
$q_result = $q->result();
if($rows>0){
foreach($q_result as $row){
$data[] = $row;
}
return $data;
}
}
i want to input data to 2 table in my localhost, from 1 page, inputpenyewa.php..
You are not passing any data to the view.
$this->load->view('tampilpenyewa');
change this line to this.
$this->load->view('tampilpenyewa',$data);
You have to get the values from db. So before this line ,get value from db as
$data['records'] = $this->model_tampil->getPenyewa();
and then load the view as above, like
$this->load->view('tampilpenyewa',$data);
Hope this helps
Regards
iijb
In the tambah function of your controller,you are directly calling the view file without giving any data to it..
Do it like this..
function tambah()
{
$ck=$this->input->post('id_penyewa');
if($ck!='')
{
$this->model_tampil->insertPenyewa();
}
$records = $this->model_tampil->getPenyewa(); // The array returned from your whatever model function
$this->load->view('tampilpenyewa',array('records' => $records));
}

Resources