i am trying to display data from two different tables
Controller:
public function index()
{
$order = DB::table('order')->get();
$order_item = DB::table('order_item')->get();
return view('admin.orders', compact('order','order_item'));
}
View:
#foreach ($order as $orders)
#foreach ($order_item as $order_items)
<tr>
<th style="padding: 20px">{{ $orders->id }}</th>
<th style="padding: 20px">{{ $order_items->order_id }}</th>
<th style="padding: 20px"> <a><i style="color: #6565D8"
class="fa-solid fa-location-dot"></i></a>
<a><i style="color: #6565D8" class="fa-solid fa-eye"></i></a>
<a><i style="color: #6565D8" class="fa-solid fa-eye"></i></a>
</th>
</tr>
#endforeach
#endforeach
the problem in "$orders->id" it duplicate data to fulfill the same rows from the other table i am getting the same data (no duplicate) from "$order_items->order_id"
how to stop solve this issue?
You should make models for Order and OrderItem and then create proper relationships for each model.
For example, here's what your models could look like:
// app/Models/Order.php
class Order extends Model
{
public function orderItems()
{
return $this->hasMany(OrderItem::class);
}
}
// app/Models/OrderItem.php
class OrderItem extends Model
{
public function order()
{
return $this->belongsTo(Order::class);
}
}
In your database, you would need an order_id column in your order_items table to connect them.
Then you can do what you want using eloquent like this:
$orders = Order::withCount('orderItems')->get();
// do stuff with $orders, which now have `order_items_count` in the results.
SOLUTION:
so because i don't have model for the data i had to queries as showing below:
$orders = DB::table('order')
->select(['complaint.id','complaint.createdDate','complaint.user_id','complaint.createdDate','complaint.complaint_title','tbl_users.phone','tbl_users.email'])
->join('tbl_users', 'complaint.user_id', '=', 'tbl_users.id')
->get();
Related
I am brand new to Livewire/Jetstream and trying to make a little inventory application to try it out. In my example below I'm trying to show inventory items from DB on a table with the ability to update the inventory name and quantity from the table without going to an edit page.
I have a nested foreach and when I render the page the input fields in the loop show the value and then disappear but the value is showing correctly in the HTML. Any help would be appreciated!
**Show Inventory**
namespace App\Http\Livewire;
use App\Models\Inventory;
use Livewire\Component;
class ShowInventory extends Component
{
public $inventories;
public function mount()
{
$this->inventories = Inventory::orderBy('name')->get();
}
public function render()
{
return view('livewire.show-inventory');
}
public function name()
{
$this->name = $name;
}
public function update($id)
{
$data = $this->validate([
'name' => 'required',
'available_on_hand' => 'required',
]);
$this->item_id = $id;
$item = Inventory::find($this->item_id);
$item->update([
'name' => $this->name,
'available_on_hand' => $this->available_on_hand,
]);
}
}
**Show Item**
namespace App\Http\Livewire;
use App\Models\Inventory;
use Livewire\Component;
class ShowItem extends Component
{
public $inventory;
public function mount(Inventory $inventory)
{
$this->inventory = $inventory;
}
public function render()
{
return view('livewire.show-item');
}
}
**Parent Blade**
<table class="table-auto">
<thead>
<tr>
<th>Name</th>
<th>Quantity</th>
<th></th>
<th>View</th>
</tr>
</thead>
<tbody>
#foreach($inventories as $inventory)
#livewire('show-item', ['inventory' => $inventory], key($inventory->id))
#endforeach
</tbody>
</table>
**Nested Blade**
<form wire:submit.prevent="update({{ $inventory->id }})">
<tr>
<td><input type="input" wire:model="name" value="{{$inventory->name}}" /></td>
<td><input type="input" wire:model="available_on_hand" value="{{$inventory->available_on_hand}}" /></td>
<td><button type="submit">Save</button></td>
<td>View</td>
</tr>
</form>
<form wire:submit.prevent="update({{ $inventory->id }})">
<tr>
<td><input type="input" wire:model="name"/></td>
<td><input type="input" wire:model="available_on_hand"/></td>
<td><button type="submit">Save</button></td>
<td>View</td>
</tr>
</form>
in component
public $name, $available_on_hand;
//....
public function getModel($modelID)
{
$model = Inventory::find($modelID);
$this->name = $model->name;
$this->available_on_hand = $model->available_on_hand;
}
as you can see, always you call the getModel method, it bind to your properties the current values of model also you can edit them and save it.
You can't use both, value attribute and the wire:model, that give you the conflicts you have now
I got this form
<div class="form-group">
<label for="clientId">Client</label>
<select name="client_id" class="form-control">
#if(count($client) == 0)
<option>There are no clients.</option>
#else
#foreach($client as $client)
<option value="{{$client->client_id}}">{{$client->client_name}}</option>
#endforeach
#endif
</select>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success">Submit</button>
</div>
Which sends the data to this controller
public function store(Request $r)
{
$validatedData = $r->validate([
'proj_title' => 'required|max:100',
'client_id' => 'required',
'proj_desc' => 'required',
]);
$currentUserId = Auth::user()->user_id;
$currentUser = User::find('username')->name;
$r['created_by'] = $currentUser;
$project = Project::create($r->all());
return redirect('/projects')->with('store','');
}
I have done a one-to-many relationship from Client to Project.
My intention is that you submit the client_id, inserts that into the db and then on the index you see the client_name relative to that client_id.
This is my index
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>Project Id</th>
<th>Title</th>
<th>Description</th>
<th>Client</th>
<th>Created by</th>
<th>Created on</th>
#if (Auth::user()->role=='admin')
<th>Admin</th>
#endif
</tr>
</thead>
<tbody class="">
#foreach ($project as $project)
<tr>
<td>{{$project->proj_id}}</td>
<td>{{$project->proj_title}}</td>
<td>{{$project->proj_desc}}</td>
<td>{{$client->client_name}}</td>
<td>{{$project->created_by}}</td>
<td>{{$project->created_at}}</td>
These are my relations:
Project model:
class Project extends Model
{
protected $primaryKey = 'proj_id';
protected $fillable = ['proj_title','proj_desc','client_id','created_by'];
public function user()
{
return $this->hasOne('App\User');
}
public function task()
{
return $this->hasMany('App\Task');
}
public function client()
{
return $this->hasOne('App\Client');
}
}
Client:
class Client extends Model
{
protected $primaryKey = 'client_id';
protected $fillable= ['client_name','client_id'];
public function project()
{
return $this->hasOne('App\Project','proj_id');
}
}
As I have it right now I get "Property [client_name] does not exist on this collection instance. (View: D:\Programas\xampp\htdocs\test5\resources\views\projects\index.blade.php)"
Relations are still a bit confusing to me so sorry if this is a very noob question.
Thanks in advance
Client relation:
public function client()
{
return $this->belongsTo('App\Client');
}
Project relation:
public function projects()
{
return $this->hasMany('App\Project','proj_id');
}
And to get client name simply use $project->client->client_name, btw. use plural, learn writing code correctly...
my MessageController is as follows:
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use App\Http\Requests;
use App\Message;
class MessageController extends Controller
{
public function CreateMessage(Request $request)
{
$meso = new Message();
$meso->body = $request['body'];
$meso->subject = $request['subject'];
$request->user()->messages()->save($meso) ;
return redirect()->route('mail');
}
public function getmailbox()
{
$message = Message::orderBy('created_at', 'desc')->get();
return view('dashboard', ['messages' => $message]);
}
}
and i am trying to retrieve the messages here in my mail.blade.php:
<table class="table table-inbox table-hover">
<tbody>
#foreach($messages as $message)
<tr class="unread">
<td class="inbox-small-cells">
<input type="checkbox" class="mail-checkbox">
</td>
<td class="inbox-small-cells"><i class="fa fa-star"></i></td>
<td class="view-message dont-show">Facebook</td>
<td class="view-message view-message"><p>{{ $message->body }}</p></td>
<td class="view-message inbox-small-cells"><i class="fa fa-paperclip"></i></td>
<td class="view-message text-right">feb 14</td>
</tr>
</tbody>
#endforeach
</table>
However this is the result i get from that query :
ErrorException in ed6d9659a06e690c67323133798cd26570bdc7a9.php line 200:
Undefined variable: messages (View: C:\xampp\htdocs\dating\resources\views\mail.blade.php)
Any help here
Laravel 5
Change the function structure :
public function CreateMessage(Request $request)
{
$meso = new Message();
$meso->body = $request['body'];
$meso->subject = $request['subject'];
$meso->save();
//$request->user()->messages()->save($meso) ;
/**
* You can get the last inserted ID
*
* If your message table having primaty key column name is id
*/
// $last_insert_id = $meso->id;
return redirect()->route('mail');
}
public function getmailbox()
{
$message = Message::orderBy('created_at', 'desc')->get();
return view('mail', ['messages' => $message]);
}
I am using codeigniter framework.I have a array of id that is to be saved in service_id column in my table. I need to store a array of id in my table. my table structure is as given below.
CREATE TABLE IF NOT EXISTS `addservice` (
`employee_id` int(10) NOT NULL,
`service_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
I wrote a controller for this like:
class service extends CI_Controller
{
public function services()
{
$id = $this->session->userdata('employee');
$id_array = json_encode($this->input->post("services"));
$data_to_store=array('employee_id'=>$id,'service_id'=>$id_array));
$this->add_service_model->save($data_to_store);
$data['addservice'] = $this->add_service_model->get_addservices();
$data['main_content'] = 'admin/service_limitation/newview';
$this->load->view('includes/template', $data);
}
}
I used json_encode function. I dont get any error but i am getting a white screen. I wrote a view file where i post my id as check box.In this view file i am posting the service_id as a array and post them to my controller. My view file are:
<table class="table table-striped table-bordered table-condensed">
<thead>
<tr>
<th class="header">Service id</th>
<th class="yellow header headerSortDown">Service name </th>
<th class="green header">Service catogary</th>
<th class="red header">Service tax</th>
<th class="red header">Service length</th>
<th class="red header">Service price</th>
<th class="red header">Actions</th>
</tr>
</thead>
<tbody>
<?php
foreach($service as $row)
{
echo '<tr>';
echo '<td>'.$row['id'].'</td>';
echo '<td>'.$row['service_name'].'</td>';
echo '<td>'.$row['category'].'</td>';
echo '<td>'.$row['service_tax'].'</td>';
echo '<td>'.$row['service_length'].'</td>';
echo '<td>'.$row['service_price'].'</td>';
echo '<td class="crud-actions">
<input type="checkbox" value="'.$row['id'].'" name="services[]"/>
</td>';
echo '</tr>';
}
?>
</tbody>
</table>
my model file
class mymodel extends CI_Model{
public function get_addservices()
{
$this->db->select('*');
$this->db->from('addservice');
$query = $this->db->get();
return $query->result_array();
}
public function save($data)
{
$insert = $this->db->insert('addservice', $data);
return $insert;
}
}
here in this file, i used a function save to save data to my table
Remove json_encode from input post and use for loop to get value of array
Controller
public function services()
$id = $this->session->userdata('employee');
$id_array = $this->input->post("services");
for ($i = 0; $i < count($id_array); $i++) {// add for loop here
if(isset($id_array[$i])&& $id_array[$i]!=""){
$data_to_store = array('employee_id' => $id, 'service_id' => $id_array[$i]);
$this->add_service_model->save($data_to_store);
}
}
$data['addservice'] = $this->add_service_model->get_addservices();
$data['main_content'] = 'admin/service_limitation/newview';
$this->load->view('includes/template', $data);
}
I have a Form that contains a Dropdown and a Submit button. Like so:
View path: webmasters/filters.blade.php
{{ Form::open() }}
{{ Form::select('filt', $Dropdown, 2) }}
{{ Form::Submit('Filter') }}
{{ Form::close() }}
And a controller that populates the Dropdown with values queried from a DB. Like so:
Controller name: WebController.php
class WebController extends BaseController {
public function getFilters() {
$filters = Dropdown::getFilters();
return View::make('webmasters.filter',['Dropdown'=>$filters]);
}
public function postFilters() {
$filt = Input::get('name'); // getting the value of the select
$filters = Dropdown::getFilters();
$query = DB::table('webmasters.top_pages')->where('filter',$filt)->limit(20)->get();
return View::make('webmasters.filter', array('query'=>$query),['Dropdown'=>$filters]);
}
}
Here is my route:
Route::resource('topPage', 'WebController#getFilters');
getFilters is a model method that queries the DB for the values that come into the dropdown.
EDIT
My View file:
{{ Form::open() }}
<p></p>
<table class='liste' style='margin-left: 0px;' cellpadding='5'>
{{ Form::select('name', $Dropdown) }}
<div>
{{ Form::Submit('Filter') }}
</div>
<tr>
<td style='background-color: #426bb3; color: white; font-weight: bold; width:16%;'>Datum</td>
<td align='left' style='background-color: #426bb3; color: white; font-weight: bold; width:12%;'>Page</td>
<td align='left' style='background-color: #426bb3; color: white; font-weight: bold; width:12%;'>Kategorie</td>
</tr>
#foreach($Webmasters as $topPages)
<tr>
<td> {{$topPages->date}} </td>
<td> {{$topPages->page}} </td>
<td> {{$topPages->category}} </td>
</tr>
#endforeach
</table><br>
{{ Form::close() }}
I would like to call a controller method upon submitting the form so that the said method queries another DB and returns a table (on the same page as the dropdown and submit button) based on the selected value of the dropdown.
Since the default Form created using Form::post() is using POST, i figured i could access the value of the select using the second method in my controller postFilters(). This method goes ahead and uses the value as a where-clause as it queries anther DB and passes the results onto a View.
The Problem is, the View is not loading. I suppose i'm doing something wrong on the routing??
Can someone help?
Your controller isn't passing to the view what the view is expecting. You inject query and the view wants $Webmasters. Also the second array with Dropdown you added won't work. This should fix the issue:
public function postFilters() {
$filt = Input::get('name'); // getting the value of the select
$filters = Dropdown::getFilters();
$query = DB::table('webmasters.top_pages')->where('filter',$filt)->limit(20)->get();
return View::make('webmasters.filter', ['Webmasters'=>$query, 'Dropdown'=>$filters]);
}
Edit
Also you're using Route::controller with a controller function. You have to pass the controller class.
Route::controller('top_page', 'WebController');
It's important that you now use top_page/filters as URL for accessing the form. (and posting it)