I have company, employee and motorCycle table.
One Company has many employee. One employee has One motorCycle
Company.php
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class Company extends Model
{
protected $table = 'company';
protected $primaryKey = '_id';
public function employee()
{
return $this->hasMany(Employee::class);
}
}
?>
Employee.php
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class Employee extends Model
{
protected $table = 'employee';
protected $primaryKey = '_id';
public function motorCycle()
{
return $this->hasOne(MotorCycle::class, 'motorCycle', 'id');
}
}
?>
MotorCycle.php
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class MotorCycle extends Model
{
protected $table = 'motorCycle';
protected $primaryKey = 'id';
public function employee()
{
return $this->belongsTo('MotorCycle::class');
}
}
?>
I would like to fetch result in controller like below
public function show(Company $company)
{
return $company->employee()->offset(0)->limit(20)->motorCycle()->get();
}
I am trying to browse this URL http://127.0.0.1:8000/api/comapanys/1
My route is like below
Route::apiResource('comapanys', 'ComapanyController');
what kind of result do you want to display? you want to have a list of employees and his/her motorcycle in a certain company?
may you can return a query like this.
public function show(Company $company)
{
return $company->employee()->with('motorCycle')->offset(0)->limit(20)->get();
}
There is to many problem in your code.
First, for example you write class company extends Model but in controller you use Company $company. Also for class employee class employee extends Model but in motoCycle class return $this->belongsTo('App\Model\Employee');. Use naming convention like first letter uppercase for model name .
Second, im not sure but I dont think you can chain eloquent methods like this return $company->employee()->offset(0)->limit(20)->motorCycle()->get();. Offset and limit should be on the end of chain.
Also use (Employee::class) instead of ('App\Model\Employee')
Related
In my model file Category.php I am extending the Category Class...
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $guarded = [];
public $timestamps = false;
public $table = "category";
public function subcategories(){
return $this->hasMany(SubCategory::class)->orderBy('name');
}
}
class ProductCategory extends Category
{
public $table = 'product_categories';
}
But when i try to access the ProductCategory Model It is not available, am i forgetting an import somewhere?
$partcategories = PartCategory::orderBy('name')->get();
This is the error i get...
Symfony\Component\Debug\Exception\FatalThrowableError
Class 'App\Http\Controllers\ProductCategory' not found
Thanks in advance!
Firstly, create a separate class file for the PartCategory, if you haven't already.
namespace App;
class ProductCategory extends Category
{
public $table = 'product_categories';
}
Secondly, where you are using the model, make sure you are importing the PartCategory class correctly:
use App\PartCategory;
Then you can use the model as you had:
$partcategories = PartCategory::orderBy('name')->get();
I'm new to laravel and just started creation of apis to connect to the database. I'm able to send a single entry at a time to the database, now what i want to do is to pass an array of data to be inserted into the database but don't seem to find my way around
Controller
public function newSaveUser(Request $request) {
$newFood = new Food;
$newFood->name = $request->name;
$newFood->save();
}
Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Food extends Model {
//
public $timestamps = false;
}
Try this here:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Food extends Model
{
//
public $timestamps = false;
protected $fillable = ['name'];
}
and then to insert data:
Food::create([
'name' => $request->get('name')
]);
firstly check the db connection is works or not.
namespace App;
use Illuminate\Database\Eloquent\Model;
class Food extends Model
{
//
public $timestamps = false;
protected $table = "write_table_name_here";
protected $guarded = [];
}
extend model in controller;
$newFood = new Food;
$newFood->name = $request->name;
$newFood->save();
I want using Eloquent ORM and Query Builder in one place (one model), Thanks
<?php
namespace App\Inventory_material;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
class InventoryMaterialModel extends Model
{
// Eloquent ORM
protected $table = 'table_name';
// Query Builder
public function getter($field, $value) {
$query = DB::table('inventory_material')->where('id', $value)->value($field);
return $query;
}
You don't need the getter method if you're using Eloquent, it is all taken care of under the hood.
class InventoryMaterialModel extends Model
{
// Eloquent ORM
protected $table = 'table_name';
}
class InventoryController
{
public function show($id)
{
return App\Inventory_material\InventoryMaterialModel::findOrFail($id);
}
}
I'm trying to get the available room at specified date by the client. So far I tried using join and left join to get the available room.
Controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\RedirectResponse;
use App\client;
use App\reservation;
use App\booking;
use App\availableRoom;
use App\roomType;
use App\amenities;
use App\payment;
use App\roomReserved;
use App\Mail\ReservationDetail;
use Carbon\Carbon;
class ReservationController extends Controller
{
private $_availablerooms;
/**
* ReservationController constructor.
*/
public function __construct()
{
$this->_availablerooms = new availableRoom();
}
/**
* #param Request $request
* #return mixed
*/
public function checkAvailable(Request $request){
$checkInDate = date("d-m-Y", strtotime($request->start_date));
$checkOutDate = date("d-m-Y", strtotime($request->end_date));
$availableRooms = $this->_availablerooms->from('availableRoom as r')
->selectRaw('*,r.roomDoorNum, r.isAvailable, rt.title as roomType,res.roomReservedID')
->join('roomtype as rt','rt.roomTypeID','=','r.roomTypeID')
->leftjoin('roomReserved as rr','rr.roomID','=','r.roomID')
->leftjoin('reservation as res','res.roomReservedID','=', DB::raw('rr.roomReservedID AND (res.reservationDate BETWEEN '."$checkInDate".' AND ' ."$checkOutDate". ' OR res.expiryDate BETWEEN '."$checkInDate".' AND ' ."$checkOutDate".')' ))
->get();
return $availableRooms;
//return view('rooms');lorem
}
}
The problem is I'm getting this error now.
SQLSTATE[42S02]: Base table or view not found: 1146 Table
'seaurchin.availableroom' doesn't exist (42S02)
availableRoom model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class availableRoom extends Model
{
protected $primaryKey = 'roomID';
protected $fillable = ['roomTypeID', 'roomDoorNum', 'isAvailable'];
public function roomAmenity()
{
return $this->hasMany('App\roomAmenity');
}
public function roomType()
{
return $this->hasOne('App\roomType');
}
public function roomAsset()
{
return $this->hasMany('App\roomAsset');
}
}
roomType model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class roomType extends Model
{
protected $primaryKey = 'roomTypeID';
protected $fillable = ['title', 'nightRate', 'capacity', 'childrenAllowed', 'maxAdult', 'description'];
public function availableRoom()
{
return $this->hasMany('App\availableRoom');
}
}
roomReserved model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class roomReserved extends Model
{
protected $primaryKey = 'roomReservedID';
protected $fillable = ['reservationID', 'roomID'];
public function reservation()
{
return $this->hasOne('App\Reservation');
}
}
reservation model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class reservation extends Model
{
protected $primaryKey = 'reservationID';
protected $fillable = ['reservationDate', 'expiryDate', 'paymentReceived', 'status', 'actualCheckIn', 'actualCheckOut', 'roomReservedID'];
public function booking()
{
return $this->hasOne('App\Booking');
}
public function roomReserved()
{
return $this->hasMany('App\roomReserved');
}
}
I have three tables and i want to make multiple relationship between then
orders,order_details,book
I want to make a common relation between then to take values in a single array .I am using following Code
Order.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
public $timestamps = false;
protected $table='orders';
public function orderDetails(){
return $this->hasMany('App\OrderDetail','order_id');
}
}
OrderDetail.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class OrderDetail extends Model
{
//
public $timestamps = false;
protected $table='order_details';
public function orders(){
return $this->belongsToMany('App\Order');
}
public function book(){
return $this->hasMany('App\Book');
}
}
and Book.php
public function orderDetail(){
return $this->hasManyThrough('App\OrderDetail','App\Book','id','item');
}
where item is foreign key and primary key in book table
in OrderController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Order,App\OrderDetail,App\Book,App\User;
use Auth;
use App\Http\Requests;
use Response;
use App\Http\Controllers\Controller;
class OrderController extends Controller
{
public function userOrders(){OrderDetail::find($orderId)->where('order_id',$orderId)->where('item','book.id')->get(); }