I have a Bank model which has 'bank_name', 'account_name' and 'balance' fields. Another model Transaction is where user first selects the bank and inputs opening_balance and transaction_amount and the closing_balance which is "opening balance +- transaction_amount" (-, + depending upon debit/credit) becomes "balance" in Bank Model. I want to show the balance in a particular bank in bank.index page by grabbing the closing_balance from transactions table. I am stuck here. So far I have:
Bank Model:
protected $fillable=['bank_name','account_name'];
public function transactions()
{
return $this->hasMany('App\Transaction');
}
Transaction Model:
protected $fillable = ['bank_id','opening_balance','transaction_amount','isdebit','closing_balance'];
public function bank()
{
return $this->belongsTo('App\Bank');
}
BankController:
public function index()
{ $banks = Bank::all();
//$bal_1 = Bank::find(1)->transactions()->latest()->first();
// I can show the balance in bank which has id 1 by this manually.
return view('bank.index', compact('banks','bal_1'));
}
Transaction Controller:
public function index()
{ $transactions = Transaction::all();
return view('transaction.index',compact('transactions'));
}
Bank.index page
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Bank Name</th>
<th scope="col">Account Name</th>
<th scope="col">Balance</th>
</tr>
</thead>
<tbody>
#foreach($banks as $i=>$bank)
<tr>
<th scope="row">{{++$i}}</th>
<td>{{$bank->bank_name}}</td>
<td>{{$bank->account_name}}</td>
<td>{{$bal_1->closing_balance}}</td>
</tr>
#endforeach
</tbody>
</table>
You can define another relation in Bank model which give you one model object instead of array like this :
public function transaction()
{
return $this->hasOne('App\Transaction');
}
Then You can use this relation in your bank.index view :
<td>{{$bank->transaction->closing_balance}}</td>
Related
Morning all.
I have created a vehicle database with somewhat detailed information like engine type, fuel, transmission, manufacturer and so on...
I started out by selecting the logo for each entry and soon realized that I will end up with a folder full of the same logos just named differently by timestamp.
I am therefore trying to create a process of manually uploading all the manufacturer logos into an assets folder then when I input the 'Manufacturer Name' it will use the information to pull the relevant logo from public/storage/assets.
My Vehicle Model
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Vehicle extends Model
{
use HasFactory; /** Name of columns fillable */
protected $table = 'vehicles';
protected $fillable = [
'make',
'model_name',
'version',
'powertrain',
'trans',
'fuel',
'model_year',
'image',
'created_at'
];
};
My VehiclesController
namespace App\Http\Controllers;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Models\Vehicle;
use Illuminate\Http\Controllers;
use Illuminate\Database\Migrations\CreateVehiclesTable;
class VehiclesController extends Controller
{
public function index()
{
return view('index');
}
/** Handle insert */
public function store(Request $request)
{
// print_r($_POST);
// print_r($_FILES);
// // }
$file = $request->file('image');
$filename = time(). '.' .$file->getClientOriginalExtension();
$file->storeAs('public/images', $filename);
// handle insert vehicle ajax request
$vehicle = Vehicle::create(
[
'make' => $request->make,
'model_name' => $request->model_name,
'version' => $request->version,
'powertrain' => $request->powertrain,
'trans' => $request->trans,
'fuel' => $request->fuel,
'model_year' => $request->model_year,
'image' => $filename
]
);
return response()->json($vehicle);
}
// FETCH ALL AJAX REQUEST
public function fetchAll()
{
$vehicles = Vehicle::all(); //Could be model or controller...
$output = '';
if ($vehicles->count() > 0) {
$output .= '<table class="table table-striped table-sm text-center align-middle" >
<thead>
<tr>
<th class="tbl-head">ID</th>
<th class="tbl-head">Image</th>
<th class="tbl-head">Make</th>
<th class="tbl-head">Model</th>
<th class="tbl-head">Derivative</th>
<th class="tbl-head">Powertrain</th>
<th class="tbl-head">Transmission</th>
<th class="tbl-head">Fuel Type</th>
<th class="tbl-head">Model Year</th>
</tr>
</thead>
<tbody>';
foreach ($vehicles as $vehicle) {
$output .= '<tr class="tbl exp_tbl">
<td>'.$vehicle->id.'</td>
<td><img src="./storage/images/'.$vehicle->image.'" class="img-thumbnail justify-content-sm-center rounded-circle"></td>
<td>'.$vehicle->make.'</td>
<td>'.$vehicle->model_name.'</td>
<td>'.$vehicle->version.'</td>
<td>'.$vehicle->powertrain.'</td>
<td>'.$vehicle->trans.'</td>
<td>'.$vehicle->fuel.'</td>
<td>'.$vehicle->model_year.'</td>
<td>
<i class="bi-pencil-square h4"></i>
<i class-"bi-trash h4"></i>
</td>
</tr>';
}
$output .= '</tbody></table>';
echo $output;
} else {
echo '<h1 class="text-center text-secondary my-5">No vehicles in the database!</h1>';
}
}
public function time($time)
{
$time->Carbon::now();
}
}
My Migration file
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateManufacturersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('manufacturers', function (Blueprint $table) {
$table->id('id');
$table->string('manu_logo');
$table->string('manu_name');
$table->timestamps('created_at');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('manufacturers');
}
}
I am under the impression that I will need to generate a new model and use the present VehiclesController to pull the logo from the manufacturers model.
I think I'm getting a little confused and would appreciate any help, if anymore information is needed please dont hesitate to ask
Thanks In Advance
there are several solutions:
a) use manufacturer id to get access to logo;
b) use manufacturer name to provide logo, but in this case you need to load manufacturer relation every time;
c) use image field to provide logo url based on manufacturer when creating Vehicle model (in other variants you don't need image field in Vehicle model or it can be used to provide vehicle photo not the manufacturer logo);
d) upload logo when creating/updating Manufacturer to use it (based on your manufacturer table migration - this is the one you want).
so
a) steps:
upload bunch of logos into public/logo folder with relevant to car manufacturer id like 1.png, 2.png etc in whatever way you want (either manually or with some form with upload request)
in your Vehicle model create getter to get access to logo url
in controller use created in step 2 getter to provide displaying of associated logo
// Vehicle Model
public function getLogoUrlAttribute() {
$path = "logo/$this->make.png";
return Storage::exists($path) ? Storage::url($path) : '';
}
// controller fetchAll() method
...
<td><img src="$vehicle->logo_url" class="img-thumbnail justify-content-sm-center rounded-circle"></td>
...
b) steps:
upload bunch of logos into public/logo folder with relevant to car manufacturer name like wv.png, audi.png etc in whatever way you want (either manually or with some form with upload request)
in your Vehicle model create getter to get access to logo url
in controller use created in step 2 getter to provide displaying of associated logo
// Vehicle Model
public function getLogoUrlAttribute() {
if (!$this->relationLoaded('manufacturer') {
return '';
}
$name = $this->manufacturer-> manu_name;
$path = "logo/$name.png";
return Storage::exists($path) ? Storage::url($path) : '';
}
// controller fetchAll() method
...
<td><img src="$vehicle->logo_url" class="img-thumbnail justify-content-sm-center rounded-circle"></td>
...
c) steps:
upload bunch of logos into public/logo folder with relevant to car manufacturer id like 1.png, 2.png etc in whatever way you want (either manually or with some form with upload request)
when creating new vihecle set path to logo into image field
// store() method
/* you don't need this anymore
$file = $request->file('image');
$filename = time(). '.' .$file->getClientOriginalExtension();
$file->storeAs('public/images', $filename);*/
$path = Storage::exists('logo/$request->make.png') ? "logo/$request->make.png" : '';
$vehicle = Vehicle::create(
[
'make' => $request->make,
'model_name' => $request->model_name,
'version' => $request->version,
'powertrain' => $request->powertrain,
'trans' => $request->trans,
'fuel' => $request->fuel,
'model_year' => $request->model_year,
'image' => $path
]
);
// fetchAll() method
...
<td><img src="Storage::url($vehicle->image)" class="img-thumbnail justify-content-sm-center rounded-circle"></td>
...
of make it even better
//Vehicle model
public function getLogoUrlAttribute() {
return Storage::url($this->image);
}
// fetchAll() method
...
<td><img src="$vehicle->logo_url" class="img-thumbnail justify-content-sm-center rounded-circle"></td>
...
d) steps:
when creating Manufacturer you uploading its logo (save it with whatever you want name as it will be tied by path)
get logo url from preloaded manufacturer relation
// ManufacturerController
public function store() {
// create new manufacturer and store provided logo image
}
// Vehicle model
public function manufacturer() {
return $this->hasOne(Manufacturer::class, 'make', 'id');
}
// Manufacturer model
public function getLogoUrlAttribute() {
return Storage::url("logs/$this->manu_logo.png");
}
// vehicle controller
public function fetchAll() {
// note preloading manufacturer relation
$vehicles = Vehicle::with('manufacturer')->get();
...
<td><img src="" . $vehicle->manufacturer->logo_url class="img-thumbnail justify-content-sm-center rounded-circle"></td>
...
}
and just to be sure avoiding n+1 request problem i'd suggest still use getter in Vehicle model for logo
// adding to Vehicle model
public function getLogoUrlAttribute() {
if (!$this->relationLoaded('manufacturer') {
return '';
}
$name = $this->manufacturer->manu_logo;
$path = "logo/$name.png";
return Storage::exists($path) ? Storage::url($path) : '';
}
// fetchAll() method
...
<td><img src="$vehicle->logo_url" class="img-thumbnail justify-content-sm-center rounded-circle"></td>
...
some thoughts about your fetchAll() method:
i'd suggest you to let blade build page for you - this will make controller nice and clear
public function fetchAll() {
// note preloading manufacturer relation
$vehicles = Vehicle::with('manufacturer')->get();
return view('vehicle-index', ['$vehicles'=>$vehicles]);
}
and all html stuff in vehicle-index.blade.php with much more pleasant to work with
<html lang="{{ app()->getLocale() }}">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta name="Pragma" content="no-cache" />
<meta name="Expires" content="0" />
<title>title</title>
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body>
#if ($vehicles->isEmpty())
<h1 class="text-center text-secondary my-5">No vehicles in the database!</h1>
#else
<table class="table table-striped table-sm text-center align-middle">
<thead>
<tr>
<th class="tbl-head">ID</th>
<th class="tbl-head">Image</th>
<th class="tbl-head">Make</th>
<th class="tbl-head">Model</th>
<th class="tbl-head">Derivative</th>
<th class="tbl-head">Powertrain</th>
<th class="tbl-head">Transmission</th>
<th class="tbl-head">Fuel Type</th>
<th class="tbl-head">Model Year</th>
</tr>
</thead>
<tbody>
<tr class="tbl exp_tbl">
<td>{{ $vehicle->id }}</td>
<td><img src="{{ $vehicle->logo_url }}" class="img-thumbnail justify-content-sm-center rounded-circle"></td>
<td>{{ $vehicle->make }}</td>
<td>{{ $vehicle->model_name }}</td>
<td>{{ $vehicle->version }}</td>
<td>{{ $vehicle->powertrain }}</td>
<td>{{ $vehicle->trans }}</td>
<td>{{ $vehicle->fuel }}</td>
<td>{{ $vehicle->model_year }}</td>
<td>
<i class="bi-pencil-square h4"></i>
<i class="bi-trash h4"></i>
</td>
</tr>
</tbody>
</table>
#endif
</body>
I am doing my assignment for a hotel booking system. I have a table named bookings and another table room. I did a one to many relations between them I want to return the room name to the home view but it is always showing Trying to get property of non-object. This is my code.
BOOKING Controllerclass GuestBookingController extends Controller
public function new()
{
$rooms = Room::all();
$guests = Guest::all();
return view('guestbookings.new', compact('rooms','guests'));
}
public function store(Request $request)
{
$validatedData = $request->validate([
'checkin_dtime' => 'required',
'checkout_dtime' => 'required',
'id_number' => 'required|unique:guests',
'mobile' => 'required',
]);
$result = Booking::where('checkin_dtime', '<=',$request->checkin_dtime)->where('checkout_dtime', '>=',$request->checkout_dtime)->where('room_id',$request->room_id)->first();
if(!$result){
$bookings = new Booking;
$bookings->checkin_dtime = $request->input('checkin_dtime');
$bookings->checkout_dtime = $request->input('checkout_dtime');
$bookings->user_id = auth()->user()->id;
$bookings->save();
$guests = new Guest;
$guests->id_number = $request->input('id_number');
$guests->mobile = $request->input('mobile');
$guests->save;
}
return redirect('home');
Home view
<table class="table table-striped">
<thead>
<tr>
<td>ID</td>
<td>Room Name</td>
<td>Check-In</td>
<td>Check-Out</td>
<td>Status</td>
<td>Action</td>
</tr>
</thead>
<tbody>
#foreach($bookings as $booking)
<tr>
<td>{{$booking['id']}}</td>
<td>{{$booking->room->room_name}}</td>
<td>{{$booking['checkin_dtime']}}</td>
<td>{{$booking['checkout_dtime']}}</td>
<td>
Booking Model
public function room()
{
return $this->belongsTo(Room::class, 'room_id');
}
public function user(){
return $this->belongsTo(User::class);
}
this is your controller code as per the question:
$bookings = new Booking;
$bookings->checkin_dtime = $request->input('checkin_dtime');
$bookings->checkout_dtime = $request->input('checkout_dtime');
$bookings->user_id = auth()->user()->id;
$bookings->save();
you are not adding any room_id column. that means your room_id is null at database. so when you are trying to call relationship, eloquent is unable to build the relationship and you are getting the error. your code should be:
$bookings = new Booking;
$bookings->checkin_dtime = $request->input('checkin_dtime');
$bookings->checkout_dtime = $request->input('checkout_dtime');
$bookings->room_id = $request->input('room_id');
$bookings->user_id = auth()->user()->id;
$bookings->save();
I fetched data from my localhost database. However, a "No data available in table" shows up in my datatables. I am having a hard time figuring out what is the problem because I don't get any errors from it. I use the function fetch in my system_model.php to fetch data from the database. Is there any way to find why values from the database are not showing?
Here is my code for my controller:
class SFM_controller extends CI_Controller {
public function __construct() {
parent::__construct();
// Load form helper library
$this->load->helper('form');
$this->load->helper('url');
// // Load form validation library
$this->load->library('form_validation');
// // Load session library
$this->load->library('session');
// Load database
$this->load->model('system_model');
}
public function index()
{
$data = array(
//'logo' => base_url()."/assets/images/logo/fams-small.png",
//'full_name' => $this->session->user_full_name,
'fo_supp' => $this->system_model->fetch('fo_supp'),
);
$this->load->view('includes/SFM/SFM_Header');
$this->load->view('includes/SFM/SFM_NavBar');
$this->load->view('SFM_view', $data);
$this->load->view('includes/SFM/SFM_Footer');
}
function logout()
{
$this->load->view('includes/Login/Login_Header'); //$data);
$this->load->view('Login_view');
$this->load->view('includes/Login/Login_Footer');
}
}
Here is my code for my Model:
class system_model extends CI_Model
{
function fetch($table, $where = null, $group_by = null, $order_by = null, $limit = null)
{
if($where != null) {
$this->db->where($where);
}
if($group_by != null) {
$this->db->group_by($group_by);
}
if($order_by != null) {
foreach ($order_by as $key => $value) {
$this->db->order_by($key, $value);
}
}
if($limit != null) {
$this->db->limit($limit);
}
$query = $this->db->get($table);
return $query->num_rows() > 0 ? $query->result() : false;
}
Here is my code for my View:
<table id="datatable-buttons" class="table table-striped table-bordered">
<thead>
<tr>
<th>Supplier Code</th>
<th>Address</th>
<th>Country</th>
<th>Description</th>
<th>Telephone Number</th>
<th>Fax Number</th>
<th>Consolidating Agent</th>
<th>Contact Person</th>
<th>Actions</th>
<th>Discount 1</th>
<th>Discount 2</th>
<th>Discount 3</th>
<th>Discount 4</th>
<th>Discount 5</th>
<th>Last Transaction</th>
<th>Old Supplier</th>
</tr>
</thead>
<tbody>
<?php if(!empty($fo_supp)): ?>
<?php foreach($fo_supp as $supp): ?>
<tr>
<td> <?=$supp->supp_code?> </td>
<td> <?=$supp->address." ".$supp->address2?></td>
<td><?=$supp->country?></td>
<td><?=$supp->description?></td>
<td><?=$supp->tel_no?></td>
<td><?=$supp->fax_no?></td>
<td><?=$supp->contact?></td>
<td><?=$supp->cons_agent?></td>
<td>$320,800</td>
<td><?=$supp->disc1?></td>
<td><?=$supp->disc2?></td>
<td><?=$supp->disc3?></td>
<td><?=$supp->disc4?></td>
<td><?=$supp->disc5?></td>
<td><?=$supp->last_trans?></td>
<td><?=$supp->supp_code2?></td>
</tr>
<?php endforeach;?>
<?php endif; ?>
</tbody>
</table>
Var dump
Why is my var dump like this? and not showing values
Pass your $data array in the view file instead of header file in controller index function.
$this->load->view('SFM_view', $data);
SOLVED!
I was passing the data to the wrong controller in which my login submit is located in another controller!
I have table displaying many rows, and I'm using pagination and sort function, also I'm using ajax to return number of rows and other ajax to return rows between two dates.
The problem is if I wanted to sort rows and in the same time show some rows between two dates this wont work with me. Because when using ajax there is no url.
public function index()
{
$checks = Checks::orderBy('id', 'asc')->get();
$checks= Checks::sortable()->paginate(10);
return view('home',compact('checks'));
}
public function showpage(Request $request)
{
if($request->ajax())
{
$checks= Checks::orderBy('id', 'asc')->paginate($request->inputpage);
return view('layouts.showcheks',compact('checks'));
}
}
public function getCheckReport(Request $request)
{
if($request->ajax()){
$New=$request->StartDate;
$Old=$request->EndDate;
$checks= Checks::whereBetween('postingdate',[$New,$Old])->sortable()->orderBy('postingdate', 'asc')->get();
return view('layouts.showcheks',compact('checks'));
}
}
showchecks.blade.php
#foreach($checks as $indexKey => $check)
<tr >
<td>{{$check->details}}</td>
<td>{{date('m/d/Y', strtotime($check->postingdate))}}</td>
<td>{{$check->description}}</td>
</tr>
#endforeach
homepage:
<table class="table" id="postTable">
<thead>
<tr>
<th>#sortablelink('details','Details')</th>
<th>#sortablelink('postingdate','Date')</th>
<th>#sortablelink('description','Description')</th>
</tr>
{{ csrf_field() }}
</thead>
<tbody>
#foreach($checks as $indexKey => $check)
<tr >
<td>{{$check->details}}</td>
<td>{{date('m/d/Y', strtotime($check->postingdate))}}</td>
<td >{{$check->description}}</td>
</tr>
#endforeach
</tbody>
</table>
{{$checks->appends(Request::input())->links()}}
use a datatable https://datatables.net/ with ajax that is the best way also u can sorting a rows also..
I got 3 tables; my tables are "cursadas","usuarios" and "materias"
"cursadas" includes:(id, user_id[is the foreign key to the column "id" of the table "usuarios"], subject_id[is the foreign key to the column "id" of the table "materias"], grade, date)
"usuarios" includes:(id,username,name,lastname,password,type,status,date)
"materias" includes:(id, career_id, name, description, hours)
This is my final table "cursadas"(with data from tables "materias" and "usuarios")
TAKE A LOOK, i need something like this:
I got this error:
I think there is an error with my query, i do not know what should i do to make this work :S
Here is my code:
My view file ("usuario"):
<input id="busqueda_tabla" type="text">
<table class="table table-hover" align="center" border="1" cellspacing="0" cellpadding="0" width="700" id="tabla_busqueda">
<thead>
<th>id</th>
<th>User</th>
<th>Subject</th>
<th>Grade</th>
<th>Date</th>
</thead>
<tbody>
<?php
if (count($records) > 0 && $records != false) {
foreach($records as $record) {
echo "<tr>
<td>".$record['id']."</td>
<td>".$record['user']."</td>
<td>".$record['name']."</td>
<td>".$record['grade']."</td>
<td>".$record['date']."</td>
</tr>";
}
}
?>
</tbody>
</body>
</html>
My controller file ("login"):
<?php
Class Login extends CI_Controller{
public function index(){
$this->load->view('login_form');
}
public function do_login()
{
// load the form_validation library
$this->load->library('form_validation');
$this->form_validation->set_rules('usuario', 'Username', 'trim|required|min_length[3]|alpha_numeric');
$this->form_validation->set_rules('contrasena', 'Password', 'trim|required|min_length[6]');
// if there is errors
if ($this->form_validation->run() == FALSE) {
// this will load your form with the errors
$this->load->view('login_form');
} else {
// if no errors we will hit the database
$user=$this->input->post('usuario', true);
$pass=$this->input->post('contrasena', true);
$cek = $this->m_login->proceso_login($user,$pass);
$hasil=count($cek);
if($hasil > 0)
{
$pelogin =$this->db->get_where('usuarios',array('username' => $user, 'password' => $pass))->row();
// here $pelogin has the id of the user
// create session like this
$this->session->set_userdata(array('id' => $pelogin->id));
if($pelogin ->type == 0)
{
// here goes the admin data
redirect('login/admin');
}
else{
//call here usuario method which has user data who logged in like
redirect('login/usuario');
// OR
// Call some method which has user data in $records and
}
}
redirect('login/index');
}
}
public function admin (){
$data['records']=$this->m_login->getDetails();
$this->load->view('admin',$data);
}
public function usuario(){
$data['records']=$this->m_login->getDetails();
$this->load->view('usuario',$data);
}
And the model file("m_login")- with the query!
<?php
class m_login extends CI_Model{
public function proceso_login($user,$pass){
$this->db->where('username', $user);
$this->db->where('password', $pass);
return $this->db->get('usuarios')->row();
}
public function getDetails()
{
$st=$this->db->SELECT('cursadas.*, usuarios.name as usuarios, materias.name as materias_name')->from('cursadas')
->join('usuarios','usuarios.id=cursadas.user_id')
->join('materias','materias.id=cursadas.subject_id')
->WHERE('cursadas.user_id=',$this->session->userdata['id'])
->get()->result_array();
return $st[0];
}
}
?>
Change the query :
$st = $this->db->SELECT('cursadas.date as date, cursadas.grade as grade, usuarios.username as user, materias.name as subject')->from('cursadas')
->join('usuarios','usuarios.id=cursadas.user_id')
->join('materias','materias.id=cursadas.subject_id')
->WHERE('cursadas.user_id=',$this->session->userdata('id'))
->get()->result_array();
return $st;
And pls check the database field type use datetime for date int for id and so as required
In the view :
<tbody>
<?php
if (count($records) > 0 && $records != false) {
$id = 1;
foreach($records as $record) {
echo "<tr>
<td>".$id."</td>
<td>".$record['user']."</td>
<td>".$record['subject']."</td>
<td>".$record['grade']."</td>
<td>".$record['date']."</td>
</tr>";
$id++;
}
}
?>