How can I establish a relationship a Model class with another model class of folder in laravel eloquent?? - laravel

Folder Structure:
app
|-Admin.php
|-Admin
|
|-Product.php
Admin.php
--------------------------------------------------------
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Admin extends Authenticatable
{
public function erp()
{
return $this->belongsToMany(Admin\Product::class);
}
}
-----------------------------------------------------------
Product.php
-----------------------------------------------------------
namespace App\Admin;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $primaryKey = 'productcode';
public $incrementing = false;
public function updatedBy()
{
return $this->belongsTo(Admin::class);
}
}
-----------------------------------------------------------
But got an error Class 'Admin::class' not found
any solution??

Use correct namespaces:
Admin model:
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Admin\Product;
class Admin extends Authenticatable
{
public function erp()
{
return $this->belongsToMany(Product::class);
}
}
Product model:
namespace App\Admin;
use Illuminate\Database\Eloquent\Model;
use App\Admin;
class Product extends Model
{
protected $primaryKey = 'productcode';
public $incrementing = false;
public function updatedBy()
{
return $this->belongsTo(Admin::class);
}
}
Or add namespace of a model as string, for example App\Admin

Please see your name space
Product.php
-----------------------------------------------------------
namespace App\Admin;
So when you call Admin::class it mean App\Admin\Admin::class
So please change your relation like this.
class Product extends Model
{
protected $primaryKey = 'productcode';
public $incrementing = false;
public function updatedBy()
{
return $this->belongsTo('App\Admin');
}
}

Related

count(): Parameter must be an array or an object that implements Countable on Laravel relationship

I have forums table, topics table and posts table. the relationship between the posts and topics to forums in one to many. I have implemented the relationship but when I try to access the topics count by doing {{count($forum->topics)}} I get this error: count(): Parameter must be an array or an object that implements Countable However, when I try accessing the posts count in the same way:{{count($forum->posts)}}, it works correctly. Please help
Forum model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Forum extends Model
{
use HasFactory;
protected $guarded = [];
public function category()
{
return $this->belongsTo('App\Models\Category');
}
public function topics()
{
return $this->hasMany('App\Models\Topic');
}
public function posts()
{
return $this->hasMany('App\Models\Post');
}
}
Topic model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Topic extends Model
{
use HasFactory;
public function forum()
{
return $this->belongsTo('App\Models\Forum');
}
}
Post Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
public function forum()
{
return $this->belongsTo('App\Models\Forum');
}
}

how to display the combined data of two tables using hasone relationship in controller

I have two tables :
employees(
employe_id(primary key),
emp_name,
pay_id
)
pays(
pay_id,
hourlyrate
)
I have this code in employemodel.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\payModel;
class employeeModel extends Model
{
protected $table='employees';
protected $primaryKey='employe_id';
public $timestamps=false;
public function pay()
{
return $this->hasOne('App\payModel','pay_id');
}
}
?>
In payModel I have this code.
and in employcontroller in have this code.
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Support\Str;
use App\Http\Requests;
use Illuminate\Http\Request;
use App\employeeModel;
use Illuminate\Support\Facades\DB;
class employeController extends Controller
{
public function display()
{
$display = employeeModel::find(1)->pay;
return $display;
}
}
When I use this I get only pays table details. I want combined result of two tables what I include in query.
When I use only $display = employeeModel::find(1); I am getting employee table details.
When in use $display = employeeModel::find(1)->pay; I am getting only pays table details?
class employeController extends Controller
{
public function display()
{
//DB::enableQueryLog();
$display = employeeModel::find(1)->pay;
return $display;
}
}
You can use with, It will combined the two table,
class employeController extends Controller
{
public function display()
{
//DB::enableQueryLog();
$display = employeeModel::with('pay')->find(1);
// dd($display);
return $display;
}
}

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'seaurchin.availableroom' doesn't exist (42S02)

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');
}
}

Multilevel Relationship in Laravel 5.1

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

Call to a member function save() on a non-object

I am building a small laravel app beginning level. I got error in code in I couldn't solve out.
Here is the code
post model
namespace App;
use Illuminate\Database\Eloquent\Model;
class post extends Model
{
public function user()
{
return $this->belongsTo('app\user');
}
}
user model
namespace App;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
class user extends Model implements Authenticatable
{
use \Illuminate\Auth\Authenticatable;
public function posts()
{
$this->hasMany('app\post');
}
}
postcontroller
namespace App\Http\Controllers;
use App\post;
use Illuminate\Http\Request;
class postcontroller extends Controller{
public function postCreatePost(Request $request){
$post = new post();
$post->body = $request['body'];
$request->user()->posts()->save($post);
return redirect()->route('dashboard');
}
}
Thank you in advance for any try from you to solve this query.
Make sure inside your user model you're returning the relationship.
class user extends Model implements Authenticatable
{
use \Illuminate\Auth\Authenticatable;
public function posts()
{
return $this->hasMany('app\post');
}
}
Your posted code doesn't have a return inside the posts function.
i think this should fix
add your table field to protected $fillable = [] array
user
namespace App;
use Illuminate\Database\Eloquent\Model;
class post extends Model
{
protected $fillable = ['body'];
public function user()
{
return $this->belongsTo('app\user');
}
}
post
namespace App;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
class user extends Model implements Authenticatable
{
use \Illuminate\Auth\Authenticatable;
protected $fillable = ['username', 'field2', 'blabla'];
public function posts()
{
return $this->hasMany('app\post');
}
}
postcontroller
namespace App\Http\Controllers;
use App\post;
use Illuminate\Http\Request;
class postcontroller extends Controller{
public function postCreatePost(Request $request){
$post = new post(['body' => $request->body]);
$request->user->posts()->save($post);
return redirect()->route('dashboard');
}
}

Resources