Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$diffi_lvl_name - php

I am getting error in Laravel 5.7 while creating relationship, I have created a relationship as: Question.php:
public function diffi_lvl() {
return $this->belongsTo('App\DifficultyLevel');
}
and DifficultyLevel.php:
public function questions() {
return $this->hasMany('App\Question');
}
after that I used:
#foreach ($questions as $question)
{{ dd($question->diffi_lvl()->diffi_lvl_name) }}
#endforeach
and QuestionController.php:
public function index()
{
$questions = Question::all();
return view('questions.index', compact('questions'));
}
difficulty level migration:
public function up()
{
Schema::create('difficulty_levels', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('diffi_lvl_name');
$table->timestamps();
});
}
and the question migration:
public function up()
{
Schema::create('questions', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->text('question');
$table->unsignedInteger('difficulty_level_id');
$table->foreign('difficulty_level_id')->references('id')->on('difficulty_levels');
$table->timestamps();
});
}
but it's giving me this error as;
Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$diffi_lvl_name
Note: I also used this {{ dd($question->diffi_lvl->diffi_lvl_name) }} getting Trying to get property of non-object

Change your relationship as follows:
public function diffi_lvl() {
return $this->belongsTo('App\DifficultyLevel', 'difficulty_level_id');
}
public function questions() {
return $this->hasMany('App\Question', 'difficulty_level_id');
}
Then, the following should work:
#foreach ($questions as $question)
{{ dd($question->diffi_lvl->diffi_lvl_name) }}
#endforeach
For more information, read the documentation on Defining Relationships.
Edit: Actually, it seems just doing the following should work:
public function diffi_lvl() {
return $this->belongsTo('App\DifficultyLevel', 'difficulty_level_id');
}
public function questions() {
return $this->hasMany('App\Question');
}

You already fixed first error with using
$question->diffi_lvl->diffi_lvl_name
And for second error there are some possibilities.
There is no DifficultyLevel attached to your Question model
We have to see your table structure.Maybe you mapped wrongly your foreign keys.Is your foreign key named "difficulty_level_id" in "questions" table?

Related

Laravel relationship return null

I have a store that is using a payment package
Now I want to show the items that were purchased, but I run into this problem
Controller
public function mycourse()
{
$courses = PurchasedCourse::where('user_id', Auth::id())
->with('course')
->get();
dd($courses);
return view('student.courses.mycourse', [
'courses' => $courses
]);
}
Model
public function course()
{
return $this->belongsTo(Course::class, 'id');
}
Migration
public function up()
{
Schema::create('courses', function (Blueprint $table) {
$table->id('id');
$table->string('name')->unique();
$table->string('start');
$table->string('end');
$table->integer('price');
$table->string('jalasat');
$table->string('zarfiat');
$table->text('tozih');
$table->integer('hit');
$table->string('department');
$table->string('thumbnail');
$table->tinyInteger('status')->default(0);
$table->string('slug')->unique();
$table->timestamps();
});
}
Your relationship method is wrong. The syntax for the belongsTo() method is
belongsTo(class, ?foreign_id, ?related_id). In your case, it should be:
public function course()
{
return $this->belongsTo(Course::class, 'course_id', 'id');
}
or just
public function course()
{
return $this->belongsTo(Course::class);
}
since your columns follow Laravel's naming conventions.

belongstoMany relatioship returning empty array, but tinker shows data

I'm trying to use a belongsToMany relation, i never had any problems with it but for some reason it returns empty now.
But, if i check with tinker, i get array with data in it returned
I've set up my relation in the User model like this:
// linking with table tag
public function tags(){
return $this->belongsToMany('App\Tag','tag_user','user_id','tag_id');
}
Tag model:
public function user(){
return $this->belongsToMany('App\User','tag_user','tag_id','user_id');
}
PostController
public function create()
{
// bringing user details to show his preferneces
$user_id = Auth::user()->user_id;
$user = User::find($user_id)->first();
//post_types
$types= PostType::pluck('name', 'post_type_id');
return view('user.create_post')->with('user', $user)->with('types',$types);
}
In view:
#foreach ($user->tags as $tag)
<label class = "btn btncategory">
<input type = "checkbox"
name = "tag_selected[]"
value = "{{$tag->tag_id}}" >
{{$tag->tag_name}}
</label>
#endforeach
Migrations
tags
Schema::create('tags', function (Blueprint $table) {
$table->increments('tag_id');
$table->string('tag_name')->unique();
$table->integer('type');
$table->integer('used_time')->default('0');
$table->timestamps();
});
Schema::create('tag_user', function(Blueprint $table){
$table->integer('user_id');
$table->integer('tag_id');
$table->primary(['user_id', 'tag_id']);
});
users
Schema::create('users', function (Blueprint $table) {
$table->increments('user_id');
$table->string('user_name')->unique();
$table->string('fname')->nullable();
$table->string('lname')->nullable();
... etc etc

Laravel 5.4 belongsToMany - show result in html

I create a many-to-many relationship, where many projects can be assigned to many users. My problem is that I do not know how to display projects assigned to a given user. . Currently, all available projects are displayed. I created pivot table, where after adding the project I store the project id and user id. This is my code:
User.php
public function projects()
{
return $this->belongsToMany('App\Project')->withTimestamps();
}
Project.php
public function users()
{
return $this->belongsToMany('App\User')->withTimestamps();
}
ProjectsController.php
public function projects()
{
$projects = Project::latest()->get();
return view('pages.projects')->with('projects', $projects);
}
migrations:
public function up()
{
Schema::create('projects', function (Blueprint $table) {
$table->increments('id');
$table->longText('p_name')->nullable();
$table->timestamps();
});
}
public function up()
{
Schema::create('project_user', function (Blueprint $table) {
$table->unsignedInteger('project_id');
$table->foreign('project_id')->references('id')->on('projects')->onDelete('cascade');
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
}
Eager load users in your controller:
public function projects()
{
$projects = Project::latest()->with('users')->get();
return view('pages.projects')->with('projects', $projects);
}
In your view:
#foreach($projects as $project)
#foreach($project->users as $user)
#endforeach
#endforeach
If you want to display projects assigned to a user you would do something like:
public function projectsByUser($userId)
{
$user = User::findOrFail($userId);
$projects = $user->projects;
return view('pages.projects')->with('projects', $projects);
}
and keep the view like:
#foreach($projects as $project)
#endforeach

Laravel 5.4: Cannot retrieve data from a relationship

I'm trying to display the name of the assignee (foreign key from Users table) of each ticket by storing each name in an array from two UNION'd tables (Accesses and Reports) but it gives me this error. ErrorException
Undefined property: stdClass::$assignee.
//HomeController
$accesses = DB::table('accesses')
->select(array('id', 'fullname','emp_id','shift','state','resolved_at', 'closed_at','assigned_to'))
->where('state','=','Assigned');
$all = DB::table('reports')
->select(array('id', 'fullname','emp_id','shift','state','resolved_at', 'closed_at','assigned_to'))
->union($accesses)
->where('state', '=', 'Assigned')
->get();
$names[] = array();
foreach ($all as $one)//store in array to display in a chart
{
$names[] = $one->assignee->name; //error here
}
//Report Model
public function assignee()
{
return $this->belongsTo(User::class, 'assigned_to');
}
//Access Model
public function assignee()
{
return $this->belongsTo(User::class, 'assigned_to');
}
//Report Migration
public function up()
{
Schema::create('reports', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->nullable();
$table->string('fullname');
$table->string('emp_id');
$table->string('shift');
$table->longText('report');
$table->string('status')->default('Pending'); //Pending, Approved
$table->string('state')->default('Open'); //Open, Assigned, Resolved, Closed
$table->date('resolved_at')->nullable();
$table->date('closed_at')->nullable();
$table->integer('assigned_to')->nullable();
$table->longText('action')->nullable();
$table->timestamps();
});
}
//Access Migration
public function up()
{
Schema::create('accesses', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->nullable();
$table->string('fullname');
$table->string('emp_id');
$table->string('shift');
$table->string('request');
$table->longText('note')->nullable();
$table->string('status')->default('Pending'); //Pending, Approved
$table->string('state')->default('Open'); //Open, Assigned, Resolved, Closed
$table->date('resolved_at')->nullable();
$table->date('closed_at')->nullable();
$table->integer('assigned_to')->nullable();
$table->longText('action')->nullable();
$table->timestamps();
});
}
It gives me this error
The results should be like this
You should use merge method of collection:
$accesses = Access::select(array('id', 'fullname','emp_id','shift','state','resolved_at', 'closed_at','assigned_to'))
->where('state','=','Assigned')
->get();
$reports = Report::select(array('id', 'fullname','emp_id','shift','state','resolved_at', 'closed_at','assigned_to'))
->where('state', '=', 'Assigned')
->get();
$all = $accesses->merge($reports);

Laravel Belongs To Not working

this should be quite simple but i don't know what wrong . i have the following migrations .
create_players_table
public function up()
{
Schema::create('players', function (Blueprint $table) {
$table->increments('id');
$table->integer('club_id');
$table->string('first_name');
$table->string('last_name');
$table->double('price', 3, 2);
$table->enum('position', ['goalkeeper','defender','Midfielder','Striker']);
$table->timestamps();
});
}
create_clubs_table
public function up()
{
Schema::create('clubs', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('location');
$table->timestamps();
});
}
The relationship is straight forward as one player has one team (One to one) and one team can have many players (One to Many ) . The problem is i want to list all the players with their respective teams but somehow i end up with errors . This is my player model .
class Player extends Model
{
public function club()
{
return $this->belongsTo('App\Club');
}
}
And here is the controller :
public function index()
{
$players=Player::find(1);
echo $players->club()->location;
}
I get this error
ErrorException in TeamController.php line 15: Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$name
Any help will be appreciated...
Your relation is not really a database relation try to make you're relation like this:
public function up()
{
Schema::create('players', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('club_id');
$table->foreign('club_id')->references('id')->on('clubs');
$table->string('first_name');
$table->string('last_name');
$table->double('price', 3, 2);
$table->enum('position', ['goalkeeper','defender','Midfielder','Striker']);
$table->timestamps();
});
}
https://laravel.com/docs/5.4/migrations#foreign-key-constraints
Player Model
class Player extends Model
{
public function club()
{
return $this->belongsTo('App\Club', 'club_id', 'id');
}
}
Player controller
public function index()
{
$players=Player::find(1);
echo $players->club->location;
}
it should be like this :
$players=Player::with('club')->find(1);
echo $players->club->location;
Try without () in ->club(),
public function index()
{
$players=Player::find(1);
echo $players->club->location;
}
As the error says, it refers to the "BelongsTo" relationship. i.e. Here ->club() returns the relationship object, not the club object. If you want to get the club object call as $players->club->location; .

Categories