one to many relationship in Laravel5 is not working properly - php

I have a collection controller
looks like this
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Middleware\Role;
use Illuminate\Support\Facades\Input;
use App\User;
use App\Invoice;
use Session;
use Validator;
class CollectionController extends Controller
{
/**
* Display a listing of the resource.
*
* #return Response
*/
public function __construct(){
$this->middleware('role:collector'); // replace 'collector' with whatever role you need.
}
public function getPayment($invoiceid){
$id =$invoiceid;
$invoice=Invoice::where('Id', $id)->with(['payments'])->get();
return View('collectionmodule/payment')->with(array('invoice'=>$invoice));
}
}
Then I have following models
Invoice
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Invoice extends Model
{
//
protected $table = 'event_invoice';
public function payments(){
return $this->hasMany('App\paymentrecieved','invoice_id');
}
public function comments(){
return $this->hasMany('App\comments','invoice_id');
}
}
Paymentrecieved
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class paymentrecieved extends Model
{
//
protected $table = 'paymentrecieved';
public function invoice(){
return $this->belongsTo('App\Invoice');
}
}
So for every Invoice there could be multiple payments .
So in My getPayment method I am writing Query like this .
$invoice=Invoice::where('Id', $id)->with(['payments'])->get();
Its getting me the Details from Invoice table . But its not getting me any Payment Details
Any one know why is this happening , According to me I have done the relationship properly
Thanks

You use Id (with uppercase) for the primary key, but the Invoice model is looking for the id (with lowercase).
You should define the primary key in the Invoice model like this:
protected $primaryKey = 'Id';

Related

Laravel / Illuminate's useWritePdo not being respected when loading relationships

I'm trying to force my application to use the write connection when running a select because of race conditions dealing with updating the data and refreshing it. I have confirmed that useWritePdo() function is being called, but I can tell it's not using the write connection because the race condition bug still exists. I don't know how to determine through var dumps whether the write connection is being used.
Here is the code I'm running, followed by the involved models. Note that forcing the write connection works if I call $portfolio->items($useWriteConn), but not $user->portfolios($useWriteConn)->with('items').
return $this->user->portfolios($useWriteConn)->with('items')->find($id);
Model User.php:
namespace App;
use App\Notifications\ResetPassword;
use App\Support\Auth\RetrievesUser;
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
/**
* Class User
* #package App
* #property integer $subscription
* #property integer $id
*/
class User extends Model implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword, UserTrait, Notifiable, HasApiTokens, RetrievesUser
public function portfolios($useWriteConn = false)
{
return ($useWriteConn)
? $this->hasMany(UserPortfolio::class, 'user')->writeConn()
: $this->hasMany(UserPortfolio::class, 'user');
}
}
Model UserPortfolio.php
namespace App;
// use App\UserCustomViews;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletes;
class UserPortfolio extends Model
{
use SoftDeletes;
public function user()
{
return $this->belongsTo(User::class, 'user');
}
public function items($useWriteConn = false, $showClosed = true)
{
$items = $this->hasMany(UserPortfolioItem::class, 'portfolio');
if ($useWriteConn)
$items->writeConn();
if (!$showClosed)
$items->open();
return $items;
}
public function scopeWriteConn($query)
{
return $query->useWritePdo();
}
}
Model UserPortfolioItem.php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletes;
class UserPortfolioItem extends Model
{
public function portfolio()
{
return $this->belongsTo(UserPortfolio::class, 'portfolio');
}
public function scopeWriteConn($query)
{
return $query->useWritePdo();
}
}
For anyone who comes across this later, I found the answer in another thread.
Eloquent pre-loading relationships against DB write connection
Model::onWriteConnection()->with(['relationship'=>function($query){
$query->useWritePdo();
}])->find($id)

Laravel Eloquent model returns null for one to many relation

I am not sure what is going on here. I am getting returns of null despite having the info in the database.
Stimuli Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Stimuli extends Model
{
protected $table = 'stimuli';
public $timestamps = false;
/**
* Get the details associated with the stimulus
*/
public function info()
{
return $this->hasMany('App\StimuliInfo', 'attribute', 'value');
}
}
StimuliInfo Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class StimuliInfo extends Model
{
/**
* Get the stimuli associated with the detailss
*/
protected $table = 'stimuli_info';
public $timestamps = false;
public function info()
{
return $this->belongsTo(Stimuli::class);
}
}
Controller
<?php
namespace App\Http\Controllers;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use App;
use Illuminate\Http\Requests;
class Labels extends Controller
{
public function index()
{
}
public function objects()
{
$stimulus = App\Stimuli::with('info')->get();
foreach ($stimulus as $stim)
{
$stimuli[] = $stim->stimulus_id;
}
return $stimuli;
shuffle($stimuli);
return view('label/objects')->with(compact('stimuli'));
}
}
Okay, so here is a test controller. For some reason, I am getting a null output for every data point. Which is odd as I can see in the DB that there is data there which is not null.
I am wondering whether I am doing something fishy in the model that is not right outputting this data.
Any help would be greatly appreciated - I am at a loss for this process

Class 'App\Post' not found [duplicate]

This question already has answers here:
Laravel - Model Class not found
(11 answers)
Closed 9 months ago.
I am working on laravel 5.2 AJAX Pagination with Jquery I have defined my post class as
Post.php
<?php
class Post extends Eloquent
{
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'posts';
/**
* Define guarded columns
*
* #var array
*/
protected $guarded = array('id');
}
BlogController.php
<?php
class BlogController extends Controller
{
/**
* Posts
*
* #return void
*/
public function showPosts()
{
$posts = Post::paginate(5);
if (Request::ajax()) {
return Response::json(View::make('posts', array('posts' => $posts))->render());
}
return View::make('blog', array('posts' => $posts));
}
}
Kindly help me where to paste this class to go right .
I know its error that model class is missing but dont know how to get rid of
My code structure is in snapshot
Thanks
Your Post.php model should be
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
//
}
In BlogController.php file add below lines on top
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Post;
Read this:- https://laravel.com/docs/5.2/eloquent
Add the namespace in the beginning of file like and use Model rather than eloquent class to extend
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model {
}
It will work for laravel >5.0 .
You should add below statements at top of your Post.php file, like this...
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
Now, in BlogController.php add the below statement at top of the file, like...
<?php
use App\Post;
will work definitely in Laravel 5>=

Find result with hasmany relationship in laravel

I am just starts a project in laravel and this is new environment for me. I am familiar with PHP and also models relationship. But the laravel structure is little bit complex for starting.
So the problem is I have a question and Course table, A single question may have more then one course so i created one more table which hold course id and question id.
Question Model
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Question extends Model{
protected $primaryKey = "id";
public function courses(){
return $this->hasMany('App\Models\CourseQuestion');
}
}
Course model
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Course extends Model {
protected $primaryKey = "id";
public function questions(){
return $this->hasOne('App\Models\CourseQuestion');
}
}
And last courseQuestion model
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class CourseQuestion extends Model {
protected $primaryKey = "id";
public function questions(){
return $this->hasOne('App\Models\Question');
}
public function courses(){
return $this->hasMany('App\Models\Course');
}
}
And my controller where i getting result -
class IndexController extends BaseController {
public function index(){
$user = Question::with('user','courses','branches')->find(100);
echo "<pre>";
print_r($user); die;
}
}
So the courses return only id of course and questions which store in third table but i want the course name respective id. Please help
Thanks.
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Question extends Model
{
protected $primaryKey = "id";
public function courses()
{
return $this->hasMany('App\Models\CourseQuestion', 'course_question_id', 'id')
->select('id', 'name');
}
}

How to access a class variable from same class

In this snippet:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product_variant extends Model
{
protected $primaryKey='variant_id';
public $translationForeignKey = $this->primaryKey;
}
This rule is not working:
public $translationForeignKey = $this->primaryKey;
How can we access this variable that is in the same scope of this class?
Either set the value in a constructor or create a getter to return the value.
// option 1
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product_variant extends Model
{
protected $primaryKey='variant_id';
public $translationForeignKey = '';
// option 1
public function __construct()
{
$this->translationForeignKey = $this->primaryKey;
}
}
// option 2, you dont even need the other property in this method, unless its value may change during execution
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product_variant extends Model
{
protected $primaryKey='variant_id';
// option 2
public function getTranslationForeignKey()
{
return $this->primaryKey;
}
}
At the time of defining the class you can only assign constant values to the class properties. Variables are not allowed here.
You need to do assignment part in the constructor.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product_variant extends Model
{
protected $primaryKey='variant_id';
public $translationForeignKey;
public function __construct()
{
$this->translationForeignKey = $this->primaryKey;
}
}

Categories