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...
Related
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();
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 have made an admin page and user page, and i want to show the list of users who have registered in database when the admin logs in.
For that i've created a model as follows,
public function regi_users(){
$q = $this->db->query("SELECT username FROM public");
return $q;
}
and this i am accessing through a view i have created, to which, when admin logs in, he is redirected, as follows,
account.php
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<?php
$this->load->model('loginmodel');
$qresult = $this->loginmodel->regi_user();
foreach ($qresult as $row) {
echo $row->username;
}
?>
</body>
but when my admin logs in, he's shown the following error,
Fatal error: Call to undefined method LoginModel::regi_user() in
E:\wamp64\www\ci\application\controllers\account.php on line 11
what am i doing wrong here? I apologize if it is a silly question but i am kind of new to php
Thank you for your suggestions
Controller
class User extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('loginmodel');
}
public function FunctionName($value='')
{
$this->data["users"] = $this->loginmodel->regi_user();
$this->load->view('account',$this->data);
}
}
Model
class Loginmodel extends CI_Model{
function __construct() {
parent::__construct();
}
public function regi_user() {
$query = $this->db->get('table_name')->result();
return $query;
}
}
View
<table class="table">
<thead>
<tr>
<th>Firstname</th>
</tr>
</thead>
<tbody>
<?php foreach ($users as $row) { ?>
<tr>
<td><?php echo $row->username; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
Your query should be like this
public function regi_users(){
return $this->db->select('username')->from('table_name')->get()->result_array();
}
controller
class User extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('YourModelName');
}
public function fetchUser()
{
$data['user']=$this->YourModelName->fetchUsers();
$this->load->view('yourViewClass',$data);
}
}
Model
class YourModelName extends CI_Model
{
function __construct()
{
$this->load->database();
}
public function fetchUsers()
{
$query = $this->db->select('*')->from('table_name');
$query=$this->db->get();
if($query->num_rows()>0)
{
$result=$query->result();
return $result;
}else{
return 0;
}
}
}
view
<table>
<thead>
<tr>
<th>Firstname</th>
</tr>
</thead>
<tbody>
<?php foreach ($user as $row) { ?>
<tr>
<td><?php echo $row->username; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
Model name should be LoginModel.php
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);
}