Call to a member function addEagerConstraints() on null laravel8 - laravel-8

i want fetch two tables data using with() but getting error as "Call to a member function addEagerConstraints() on null "
I have author model with multiple post relationship
My model relation as follows as follows:
Post relationship :
class Post extends Model
{
use HasFactory;
public function author(){
$this->belongsTo(Author::class);
}
}
Author model as follows:
class Author extends Model
{
use HasFactory;
public function post(){
return $this->hasMany(Post::class);
}
}
my migration of post table as follows:
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('cat');
$table->timestamps();
$table->unsignedBigInteger('author_id');
$table->foreign('author_id')->references('id')->on('authors');
});
I am trying to fetch data in controller as follows using with() in postcontroller
public function index(){
return $data = Post::with('author')->get();
}
But getting error as Call to a member function addEagerConstraints() on null . Anyone have idea what is wrong in that then please let me know.

Can you try adding a return statement;
class Post extends Model
{
use HasFactory;
public function author(){
return $this->belongsTo(Author::class);
}
}

Related

Why is my Eloquent Relation not filling all of my objects?

I have a "types" table which contains only ID and Name, the relation works on the first object but returns null on the following objects. Here is what my JSON looks like:
{"id":1,"type_id":1,"name":"test1","enabled":1,"measurement_type":{"id":1,"name":"test"}},
{"id":2,"type_id":2,"name":"test2","enabled":0,"measurement_type":null}]},
{"id":3,"type_id":1,"name":"test3","enabled":1,"measurement_type":null}]}
Here are my relations:
MeasurementFields Model
public function measurement_type() {
return $this->belongsTo(MeasurementType::class, 'type_id');
}
MeasurementTypes Model
public function measurement_type() {
return $this->belongsTo(MeasurementData::class);
}
In this Model I already have a measurement_field function which declares a belongsTo to MeasurementData (different Model) So, how do I name the new function with hasMany for types?
My Controller:
public function index()
{
return JsonResource::collection(MeasurementField::with('measurement_type')->get());
}
They all contain data, as you can see from the JSON, the relation just doesn't do anything with it.
My migrations:
Schema::create('measurement_types', function (Blueprint $table) {
$table->id()->autoincrement();
$table->string('name');
});
Schema::create('measurement_fields', function (Blueprint $table) {
$table->id()->autoincrement();
$table->foreignId('type_id')->constrained('measurement_types');
$table->string('name')->unique();
$table->boolean('enabled');
});
I think your measurement_type has many measurement_field.
and I guess you have to put this in your MeasurementField Model:
public function measurement_type() {
return $this->belongsTo(MeasurementType::class, 'type_id');
}

Set & Get session variable value

I am setting session variable in function of a controller like below.
use Illuminate\Support\Facades\Session;
class UserController extends Controller
{
public function store(Request $request)
{
session(['user_name' => $user_name]);
}
}
I am trying to access that session variable in another function of another controller.
use Illuminate\Support\Facades\Session;
class DashboardController extends Controller
{
public function __construct()
{
dd(session('user_name')); // I am not getting value here
}
}
I am not getting value from Session Variable.
You can do it like this
use Illuminate\Support\Facades\Session;
class UserController extends Controller
{
public function store(Request $request)
{
session()->put('user_name', $user_name);
}
}
And you can get it another controller or anywhere like this
session()->get('user_name');
Hope this will help you, thanks..

override relation in Laravel

I am working on limiting access depending on user roles.
I want to be able to somehow override a belongsToMany relation to return all, if user->isAdmin() returns true.
Currently have as the AccountController index method:
public function index()
{
if(Auth::user()->isAdmin()) // can this go in beforeFilter?
return Account::all();
else
return Auth::user()->accounts;
}
in my User model:
public function accounts()
{
return $this->belongsToMany("Account");
}
Is there a neat way to do this without needing an if statement in the controller functions?
You cannot do this.
The relation method must return an instance of Relation, otherwise it throws an error.
There's nothing stopping you from creating a separate method for this:
AccountController.php:
public function index()
{
return Auth::user()->userAccounts();
}
User.php:
public function accounts()
{
return $this->belongsToMany("Account");
}
public function userAccounts()
{
if ($this->isAdmin()) return Account::all();
return $this->accounts;
}

Please explain the foreign_key and local_key in Laravel ORM relationships

I'm effectively trying to define the relationships between users (sender and recipient) and messages.
My Messages migration is:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMessagesTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
//
Schema::create('messages', function($t){
$t->increments('id');
$t->integer('sender_user_id')->unsigned();
$t->integer('recipient_user_id')->unsigned();
$t->string('subject');
$t->text('content');
$t->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
//
Schema::dropIfExists('messages');
}
}
My Message model was straightforward:
<?php
class Message extends Eloquent{
// link to sender user id
public function from(){
return $this->hasOne('User', 'sender_user_id');
}
// link to recipient user id
public function to(){
return $this->hasOne('User', 'recipient_user_id');
}
}
But I'm unsure in defining the hasMany relationships in my User model.
The docs (http://laravel.com/docs/eloquent#relationships) shows the following:
return $this->hasMany('Comment', 'foreign_key');
return $this->hasMany('Comment', 'foreign_key', 'local_key');
Now, I'm confused which key is which in the latter hasMany relationship. Which is correct for my User model?
public function sentMessages(){
return $this->hasMany('Messages', 'id', 'sender_user_id');
}
public function sentMessages(){
return $this->hasMany('Messages', 'sender_user_id', 'id');
}
You have to set your relation like this:
public function sentMessages()
{
return $this->hasMany('Messages', 'sender_user_id');
}
public function receivedMessages()
{
return $this->hasMany('Messages', 'recipient_user_id');
}

Laravel Eloquent, return JSON with "belongsTo" object?

I have two models with a one-to-many relationship.
class User extends ConfideUser {
public function shouts()
{
return $this->hasMany('Shout');
}
}
class Shout extends Eloquent {
public function users()
{
return $this->belongsTo('User');
}
}
This seem to work fine.
BUT, How do I get this to return the users object nested in the shout objects?
Right now it only returns all my Shouts, but I have no access in the JSON to the belonging user model.
Route::get('api/shout', function() {
return Shout::with('users')->get();
});
This just returns this JSON, with no user object for every shout:
[{"id":"1","user_id":"1","message":"A little test shout!","location":"K","created_at":"2013-05-23 19:51:44","updated_at":"2013-05-23 19:51:44"},{"id":"2","user_id":"1","message":"And here is an other shout that is a little bit longer...","location":"S","created_at":"2013-05-23 19:51:44","updated_at":"2013-05-23 19:51:44"}]
I was having the same trouble using Laravel 5. Just wanted to add that I got it to work by using the Model::with("relationship")->get() method on the model.
I figured it out.
The method needs to be named user() not users() when working with "belongsTo" relationship.
Makes sense.
And seems to work.
If you are using:
protected $visible = ['user'];
Don't forget to add there relationship, to be visible in JSON
u can use protected $with = ['users']; on Class Shout and use protected $with = ['shouts'];.
and Give Full namespace model name
class Shout extends Eloquent {
protected $with = ['users'];
public function users()
{
return $this->belongsTo('App\User');
}
}
and
class User extends ConfideUser {
protected $with = ['shouts'];
public function shouts()
{
return $this->hasMany('App\Shout');
}
}
Receive It
Route::get('api/shout', function() {
return Shout::all()->toJson;
});