RelationNotFoundException Call to undefined relationship Laravel - php

Why i am getting error for Laravel relationship. I am trying to print_r the values with this relationship. is there any way to get rid of this error?
Controller: this is cart page functions
public function cart_page()
{
$session_id = Session::get('session_id');
$viewData = cartmodel::with('product_tbls')->where('session_id', $session_id)->get();
echo "<pre>";
print_r($viewData);
die;
// return view('pages.cart', compact('viewData'));
}
Products_model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class product_models extends Model
{
protected $table = "product_tbls";
public function shop_product_all()
{
return $this->hasMany('App\cartmodel');
}
}
Cart model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class cartmodel extends Model
{
protected $table = "shoppingcart";
public function shopcart_product()
{
return $this->belongsTo('App\product_models');
}
}

You're calling a relationship which isn't defined. I think you're passing table name in with which should be relationship function as vivek_23 mentioned in comment. So try the below code:
public function cart_page()
{
$session_id = Session::get('session_id');
$viewData = cartmodel::with('shopcart_product')->where('session_id', $session_id)->get();
echo "<pre>";
print_r($viewData);
die;
// return view('pages.cart', compact('viewData'));
}

After fixing with('shopcart_product'), I just append product_id in model like,
public function shopcart_product()
{
return $this->belongsTo('App\product_models', 'product_id);
}
Now getting values from product_tbls

Related

Laravel - Eloquent Relationship not working One to Many relationship

I have two models with One-to-Many relationship. I want to display data with relationship in blade.
Products Table
Table name = Products
PrimaryKey = pro_id
ForeignKey = cat_id
Categories Table
Table name = categories
PrimaryKey = cat_id
Products Model Code
namespace App;
use Illuminate\Database\Eloquent\Model;
class productsModel extends Model
{
//code...
protected $table = 'products';
protected $primaryKey = 'pro_id';
// Every Products Belongs To One Category
public function category()
{
# code...
return $this->belongsTo('APP\abcModel','cat_id');
}
}
Categories Model Code
namespace App;
use Illuminate\Database\Eloquent\Model;
class categoryModel extends Model
{
//code...
protected $table = 'categories';
protected $primaryKey = 'cat_id';
// One Category Has Many Products
public function products()
{
# code...
return $this->hasMany('App\productsModel','cat_id','pro_id');
}
}
Controller Code
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\productsModel;
class productsController extends Controller
{
//code...
public function products($category_id='')
{
# code...
$data["products"] = productsModel::where
('cat_id',$category_id)
->get();
$data["categories"] = productsModel::where
('cat_id',$category_id)->first()->category;
echo "<pre>";
print_r($data);
echo "</pre>";
}
}
ERROR:
Symfony\Component\Debug\Exception\FatalThrowableError
Class 'APP\categoryModel' not found
Seems that sometimes you have App, sometimes APP, while PHP is not case sensitive on class names, you might use an operating system (Linux?) that is case sensitive in terms of file names.
I would recommend to have only App everywhere, your error message clearly indicates: APP.
You can clearly see in your model files the namespace is written as "namespace App;"
There you defined the namespace for the app folder. So when you are using this model anywhere, you need to write it as you have defined the namespace. Therefore "App\categoryModel".
Your code should be as follows:
public function category()
{
# code...
return $this->belongsTo('App\categoryModel','cat_id');
}
Also a sincere request, as #alithedeveloper mentioned please follow PSR standards for writing code.
public function category()
{
return $this->belongsTo(abcModel::class,'cat_id');
}
public function products()
{
return $this->hasMany(productsModel::class,'cat_id');
}

How to get first row in Laravel relationship

How can i create a method in my model below that consist of first value of pages?
I want my cover method to get he first instance of pages.
Here's my model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Book extends Model
{
protected $guarded = [];
public function pages()
{
return $this->hasMany('\App\Page');
}
public function cover()
{
//first page of pages here
}
}
Use the first() method on the relationship
public function cover()
{
return $this->pages()->first();
}

Relationship table not recognized in Laravel 5

I have defined the following relationships to my models A & B:
Model A
namespace App;
use Illuminate\Database\Eloquent\Model;
class A extends Model {
protected $table = 'list';
public function b(){
return $this->hasMany('App\B', 'id', 'id');
}
}
Model B
namespace App;
use Illuminate\Database\Eloquent\Model;
class B extends Model
{
protected $table = 'project';
public function a(){
return $this->belongsTo('App\A', 'id', 'id');
}
}
I am trying to get the sum from the model B based on the selection from the model A. However, it returns an error as Undefined property: Illuminate\Database\Eloquent\Collection::$b
Controller
public function index()
{
$all = A::all()->count();
$large = A::where('class', 'L')->count();
$medium = A::where('class', 'M')->count();
$lg = A::where('class','L')->get();
$amount = $lg->b->sum('value');
return view('srl')->with('large', $large)
->with('medium',$medium)
->with('all',$all)
->with('amount',$amount);
}
The problem is in this line $amount = $lg->b->sum('value');. The relationship seems not working due to some reason. Any suggestions would be appreciated.
You're trying to get a relationship on a collection, the relationship exists on the objects (records) inside that collection. You need to loop over the $lg results, and for each one get their b values.
Something like this:
$lg = A::where('class','L')->get();
$amount = 0;
foreach($lg as $item)
{
$amount += $item->b->value;
}
Thanks #James ... I had to double loop to get it work. I don't know why I had to loop it twice.

Call to a member function save() on null laravel

Hello guys I'm using laravel 5 polymorphic relation to save the data in the database but I'm facing some problem. When ever I try to save the data in the database it is throwing me this error
Call to a member function save() on null
I don't know why I'm facing this error. I'm following this tutorial fot the polymorphic relation Creating Polymorphic Relations in Laravel 5.
I 'm making a polymorphic relation like this. A post and comment can have many likes.
The like Request validates that if I'm sending a id then this request should be entertained otherwise not
Like Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Requests\LikeRequest;
use App\Commands\LikeCommand;
// use App\Commands\ReadLikeCommand;
use App\Http\Controllers\Controller;
use Illuminate\Bus\Dispatcher;
// use App\Transformers\PostTransformer;
use Exception;
// use App\Events\TestEvent;
use App\Exceptions\Custom\NotPermissionException;
use App\Exceptions\Custom\NameNotFound;
class LikeController extends Controller
{
public function likeComment(LikeRequest $data){
try{
$render = $this->dispatch(new LikeCommand("comment" , $data));
}catch(Exception $e){
$e->getMessage();
}
}
public function likePost(LikeRequest $data){
error_log("1");
try{
$render = $this->dispatch(new LikeCommand("post" , $data));
}catch(Exception $e){
error_log("error : ".$e->getMessage());
}
}
}
Like Command
<?php
namespace App\Commands;
use App\Commands\Command;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Foundation\Bus\DispatchesJobs;
use App\Repositories\LikeRepository;
use Exception;
use DB;
use App\LikeModel;
use Artisan;
use App\Repositories\PostRepository;
class LikeCommand extends Command implements SelfHandling
{
use DispatchesJobs;
private $postId;
private $action;
private $data;
/**
* Create a new command instance.
*
* #param $request
*
* #internal param $email
* #internal param $phone
* #internal param $comments
* #internal param $name
*/
public function __construct($action,$request)
{
$this->action = $action;
$this->postId = $request->id;
$this->data = $request;
error_log("Hello in the construct");
}
/**
* Execute the command.
*
* #param TestRepository $TestRepository
*/
public function handle(LikeRepository $LikeRepo, PostRepository $postRepo )
{
error_log("Hello");
error_log("A : ".$this->action );
error_log("ID : ".$this->postId);
if($this->action =="comment"){
error_log("in like comment");
return $LikeRepo->LikeComment( $this->postId);
}else if ($this->action == "post"){
error_log("2");
return $LikeRepo->LikePost( $this->postId, $postRepo , );
}
}
}
Like Repo
<?php
namespace App\Repositories;
use App\Repositories\CommentRepository;
use App\Repositories\PostRepository;
use App\CommentModel;
use App\LikeModel;
class LikeRepository
{
public function create($comment)
{
// error_log("Trying to save now. Let's see");
$Like = new LikeModel;
$Like->post_id = $comment;
// $Comment->post_id = $this->post_id;
$comment->save();
}
public function LikeComment($id) {
// return CommentModel::where('post_id' , $id)->get();
// return CommentModel::get();
}
public function LikePost($id, PostRepository $postRepo){
error_log("3");
$result = $postRepo->getById($id);
error_log("4");
// $Like = DB::transaction(function () use ($LikeRepository) {
$Like = new likeModel;
error_log("5");
$result->Like->save($like);
error_log("6");
$Like->status="success";
// });
return $Like;
}
}
Like Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class LikeModel extends Model
{
public $table = "likes";
//
public function likeable()
{
return $this->morphTo();
}
}
Post Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class PostModel extends Model
{
//
public $table = "posts";
public function likes()
{
return $this->morphMany('App\Like', 'likeable');
}
}
Comment Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class CommentModel extends Model
{
//
public $table = "comments";
public function likes()
{
return $this->morphMany('App\Like', 'likeable');
}
}
Update
I solved this problem by changing $result->Like->save($like); to this $result->likes->save($like); and int he PostModel I had to change App\Likes to App\LikeModel similarly in CommentModel but now it's throwing me this error error : Method save does not exist.
Your problem in updated version was getting collection of likes but not relation which you need to run $relation->save($like).
See updated code below:
public function LikePost($id, PostRepository $postRepo){
$result = $postRepo->getById($id);
$Like = new likeModel;
error_log("5");
$result->likes()->save($Like);
error_log("6");
$Like->status="success";
return $Like;
}

Laravel Relationships Between Two Models

I am struggling with working with relationships right now and would like some help as for how to make this relationship work. I am using Laravel.
Lets say you have a staff model that looks like so:
Staff.php
class Staff extends \Eloquent {
protected $fillable = [];
public function status()
{
return $this->belongsTo('Staff_status');
}
}
The database table for the staff is as follows:
Table Name: staff
Fields: id, staffer_name, status_id
You also have a staff status model represented below:
Staff_statuses.php
class Staff_status extends Eloquent {
public function staff()
{
return $this->hasMany('Staff');
}
}
You also have a staff database table like so:
Table Name: staff_statuses
Fields: id, status_name
However when I try and load the staff controller index method it says class Staff_status is not found.
Any idea why?
You have used Staff_statuses.php as the name of your model but you are using Staff_status in the class name and thus you are calling it using Staff_status from your controller as well. This is the problem.
Change the file name to match the class name. For example, use something like this:
// StaffStatus.php
class StaffStatus extends Eloquent{
protected $table = 'staff_statuses';
public function staff()
{
return $this->hasMany('Staff');
}
}
// Staff.php
class Staff extends Eloquent {
protected $table = 'staff';
protected $fillable = [];
public function status()
{
return $this->belongsTo('StaffStatus');
}
}
In the controller you may use something like this:
$staffStatus = StaffStatus::all();
$staff = Staff::all();
namespace App;
use Illuminate\Database\Eloquent\Model;
class Photo extends Model
{
public function imageable()
{
return $this->morphTo();
}
}
class Staff extends Model
{
public function photos()
{
return $this->morphMany('App\Photo', 'imageable');
}
}
class Product extends Model
{
public function photos()
{
return $this->morphMany('App\Photo', 'imageable');
}
}

Categories