Retrieving Values from mysql table in laravel - 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]);
}

Related

Getting data from mutliple tables casuing duplicated data in view

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();

Laravel/Livewire Nested Input Fields Disappear on Page Load

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

Submit user id and display username?

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...

Undefined variable (Codeigniter)

I have this error in my view and cannot find out where is the problem:
MY Controller name 'Question':
public function show_all_question_set() {
$data = array();
$data['question_set'] = $this->Question_Model->select_all_question_set();
$this->load->view('question/make_set', $data);
}
My Model name 'Question_Model':
public function select_all_question_set() {
$this->db->select('*');
$this->db->from('tbl_question_set');
$query_result = $this->db->get();
$result = $query_result->result();
return $result;
}
My view name 'make_set':
<?php
foreach ($question_set as $all_set) {
?>
<tr>
<td align="center">
<em class="fa fa-pencil"></em>
<em class="fa fa-trash"></em>
</td>
<td> <?php echo $all_set->exam_name; ?> </td>
<td> <?php echo $all_set->subject_name; ?> </td>
<td> <?php echo $all_set->set_name; ?> </td>
<td align="center">
<em class="fa fa-book"> দেখুন </em>
</td>
</tr>
<?php } ?>
Table : tbl_question_set(set_id, exam_name, subject_name, set_name)
$this->load->model('Question_Model');
add this line to load the model if model is not autoloaded.
i think you are getting error because you write model name in capital letter.. please try this. paste this code in your model hopefully it will work..
public function show_all_question_set() {
$data = array();
$data['question_set'] = $this->question_model->select_all_question_set();
$this->load->view('question/make_set', $data);
}

CAKEPHP: Using two Models to Show data in one table using one View and one Controller ERROR: Undefined variable: total_hours

What I am trying to do is Getting fetchdata function from Attendence Model and fetch function for Employee Model
My Problems:-
Problem 1
Notice (8): Undefined variable: total_hours [APP\View\Employees\index.ctp, line 32]
Problem 2
The Values are not getting inserted in the same table
EmployeesController.php
<?php
class EmployeesController extends AppController {
public $uses = array('Employee', 'Attendence');
public function add()
{
if($this->Employee->add($this->request->data)==true){
$this->redirect(array('action'=>'index'));
}
}
public function index(){
$this->set('employees',$this->Employee->Fetch());
$this->set('attendence',$this->Attendence->fetchdata());
}
}
Attendence.php (MODEL)
class Attendence extends AppModel {
function add($data){
if (!empty($data)) {
$this->create();
if($this->save($data)) {
return true ;
}
}
}
function fetchdata() {
return $this->find('all', array('conditions' => array('Attendence.date' > '2014-04-23',
'AND' => array('Attendences.date' < '2014-04-30')
)));
}
}
Employee.php (Model)
class Employee extends AppModel {
function add($data){
if (!empty($data)) {
$this->create();
if($this->save($data)) {
return true ;
}
}
}
function Fetch() {
return $this->find('all', array(
'fields' => array('Employee.id', 'Employee.firstname','Employee.lastname','Employee.salary') )
);
} }
index.ctp(VIEW attached with EmployeesController)
<div class="index">
<table>
<thead>
<th>Num</th>
<th>Employee</th>
<th>Start Date</th>
<th>End Date</th>
<th>Salary/Hour</th>
<th>Total Hour</th>
<th>Total Salary</th>
</thead>
<?php
$id = 0;
foreach($employees as $e):?>
<? $id++ ?>
<tr>
<td><?php echo $e{'Employee'}{'id'} ?></td>
<td><?php echo $e['Employee']['firstname'], $e['Employee']['lastname'] ?></td>
<td>2014-04-24</td>
<td>2014-04-29</td>
<td style="text-align:center"><?php echo $e['Employee']['salary'] ?></td>'
</tr>
<?php endforeach; ?>
<?php foreach ($attendence as $et){
$ts1 = strtotime($et['Attendence']['in_time']);
$ts2 = strtotime($et['Attendence']['out_time']);
$diff = abs($ts1 - $ts2) / 3600;
$total_hours += number_format($diff,2);
}
//Total hours
echo '<td style="text-align:center">'.$total_hours.'</td>';
//Total Salary
echo '<td style="text-align:center">'.$total_hours*$e['Employee']['salary'].'</td>';
?>
</table>
</div>
<div class="actions">
<h3>Actions</h3>
<ul>
<li>New Employee</li>
<li>Attendance</li>
<li>Salary Calculator</li>
</ul>
</div>
You are using/incrementing a variable that isn't initiated yet.
update this line:
<?php foreach ($attendence as $et){
to:
<?php $total_hours = 0; foreach ($attendence as $et){

Categories