How can i get data using Eloquent Relationships in laravel - php

I need to get data from the teaching_subjects table to my Vue file according to teacher table data. I have created the relationship with the TeachingSubject model and Teacher model.
This is my Teacher Model,
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Teacher extends Model
{
protected $table = 'teacher';
protected $fillable = [
'firstName',
'lastName',
'teacherUserName',
'contactNo',
'teacherEmail',
'gender',
'teaching_expirence',
'Qualifications',
'description',
'speakEnglish',
'speakJapan',
'password',
'status',
];
public function approvalStatus(){
return $this->belongsTo(ApprovalStatus::class);
}
public function teachingSubject(){
return $this->hasMany(Teacher::class);
}
}
And this is my TeachingSubject Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class TeachingSubject extends Model
{
protected $table = 'teaching_subjects';
protected $fillable = [
'teacher_id',
'subject_id',
'lesson_fee'
];
public function teacher(){
return $this->hasMany(Teacher::class);
}
public function subject(){
return hasMany(Subject::class);
}
}
This is my Subject model,
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Subject extends Model
{
protected $table = 'subject';
protected $fillable = [
'subject',
'grade_id',
'no_of_teachers',
'status'
];
public function teachingSubject(){
return belongsTo(TeachingSubject::class);
}
}
This is my Teching_subjects migration file
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateTeachingSubjectsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('teaching_subjects', function (Blueprint $table) {
$table->integer('id')->unsigned()->autoIncrement();
$table->integer('teacher_id')->unsigned();
$table->integer("subject_id")->unsigned();
$table->float("lesson_fee")->nullable();
$table->timestamps();
$table->foreign('teacher_id')
->references('id')->on('teacher');
$table->foreign('subject_id')
->references('id')->on('subject');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('teaching_subjects');
}
}
I need to get the date(created_at), teacher_name, lesson and lesson_fee using TeachingSubjectController.

for example if You want to get user that made the comment, so get that user from the comment object.
Try this
$user = User::find(1);
$posts = $user->posts;
foreach ($posts as $post) {
foreach ($post->comments as $comment) {
echo $comment->commentcontent;
echo $comment->users;
}
}

Related

ErrorException Trying to get property 'User' of non-object ( laravel )

I am getting the error:
ErrorException Trying to get property 'User' of non-object
from the statements below which don't seem to work:
$user = Mobile::find(3)->User;
dd($user);
rest of the code is as follows:
usercontroller.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Mobile;
use Hash;
class UserController extends Controller
{
public function addUserMobile()
{
$user = new User;
$user->name = "Test Name";
$user->email = "test#mnp.com";
$user->password = Hash::make("12345678");
$user->save();
$mobile = new Mobile;
$mobile->mobile = '123456789';
$user->mobile()->save($mobile);
}
public function index()
{
// get user and mobile data from User model
$user = User::find(3);
// var_dump($user->name);
// var_dump($user->mobile->mobile);
// // get user data from Mobile model
$user = Mobile::find(3)->User;
dd($user);
// // get mobile number from User model
// $mobile = User::find(3)->mobile;
// dd($mobile);
}
}
mobile.php
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function mobile()
{
return $this->hasOne(Mobile::class);
// note: we can also inlcude Mobile model like: 'App\Mobile'
}
}
mobile table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateMobilesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('mobiles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->string('mobile');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')
->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('mobiles');
}
}
mobile database
user database
"3" is user_id btw.
The problem is you are querying the Mobile with id 3 (which does not exist) and then calling the user relation.
$user = Mobile::find(3)->user;
Since Mobile::find with an id that doesn't exist returns null, you are calling ->user on null, and you will get the error you mentioned.
Also, you should add a belongsTo relation in your Mobile model:
public function user()
{
return $this->belongsTo(User::class);
}
Now, after fixing your query to use user_id, you can do:
$user = Mobile::where('user_id', 3)->first()->user;

Call to a member function attach() on boolean - Laravel

i have a problem with function attach(). I have created 3 tables. 1 table is for added movies. Table 2 applies to the movie categories. 3 table is a collection of movie ID and category ID. A combination of many to many.
When i want add a new video with category from form this i have error -> Call to a member function attach() on boolean. If anyone knows the answer, please help. Thank you for your time!
VideoController.php -> look at the method store();
<?php
namespace App\Http\Controllers;
use Request;
use App\Http\Requests\CreateVideoRequest;
use App\Video;
use App\Category;
use Auth;
use Session;
class VideoController extends Controller
{
public function __construct(){
$this->middleware('auth', ['except' => 'index']);
}
public function index(){
$videos = Video::latest()->get();
return view('videos.index')->with('videos', $videos);
}
public function show($id){
$video = Video::find($id);
return view('videos.show')->with('video', $video);
}
public function create(){
$categories = Category::pluck('name', 'id');
return view('videos.create')->with('categories',$categories);
}
public function store(CreateVideoRequest $request){
$video = new Video($request->all());
//dd($request->all());
Auth::user()->videos()->save($video);
$categoryIds = $request->input('CategoryList');
$video->categories()->attach($categoryIds);
Session::flash('video_created', 'Added');
return redirect('video');
}
public function edit($id){
$video = Video::findOrFail($id);
return view('videos.edit')->with('video', $video);
}
public function update($id, CreateVideoRequest $request){
$video = Video::findOrFail($id);
$video->update($request->all());
return redirect('video');
}
}
Video.php - model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Video extends Model
{
protected $fillable = [
'title',
'url',
'description'
];
public function user(){
return $this->belongsTo('App\User');
}
public function categories(){
return $this->belongsToMany('App\Video')->withTimestamps;
}
}
Category.php - model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $fillable = [ 'name' ];
public function videos(){
return $this->belongsToMany('App/Video')->withTimestamps;
}
}
User.php - model (maybe you need a User.php model solves problems)
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function videos(){
return $this->hasMany('App\Video');
}
}
Migration - create_category_video_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCategoryVideoTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('category_video', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('category_id');
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
$table->unsignedBigInteger('video_id');
$table->foreign('video_id')->references('id')->on('videos')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('category_video');
}
}
Migration - create_categories_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCategoriesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('categories');
}
}
Migration - create_videos_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateVideosTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('videos', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->string('title');
$table->string('url');
$table->text('description');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('videos');
}
}
form.blade.php - simple form in Laravel Collection
{!! Form::select('CategoryList', $categories, null, ['multiple' => 'multiple']) !!}
For the timestamps for the pivot you would call the "method" withTimestamps() not a "property" named withTimestamps:
// Video
public function categories()
{
return $this->belongsToMany(Category::class)->withTimestamps();
}
// Category
public function videos()
{
return $this->belongsToMany(Video::class)->withTimestamps();
}

Relation one to many it doesn't work

https://imgur.com/a/ob9rjIz
There are two tables one called user and another called user_relation_user
My relation is an user to many user_relation_user and in my migration. I want to create 10 user with php artisan tinker so i run factory(App\User::class, 10)->create(); at the end i access to my database so do select * from users there are 10 users but in user_relation_user isn't 10 id or it's empty
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Administrator extends Model
{
protected $table = 'user_relation_user';
protected $primaryKey = 'id';
protected $fillable = ['user_id'];
public function users(){
return $this->belongsTo(User::class,'user_id');
}
}
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function administrator(){
return $this->hasMany(Administrator::class,'user_id');
}
}
//hasMany
My migration
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUserRelationUserTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('user_relation_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('user_id_admin')->unsigned();
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*foreign
* #return void
*/
public function down()
{
Schema::dropIfExists('user_relation_user');
}
}
The relation you define is correct,you just need to define a relation in user model as well.
Example:
Suppose you are developing a blog system where user can post blogs.
then there will be two models user model and blog model
In User model you have to define user relation as below:
public function blogs()
{
return $this->hasmany(Blog::class);
}
Then in blogs model
public function users()
{
return $this->belongsTo(User::class);
}

Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$name laravel 5.4

Hi following are my relations
User Model
public function loginlogout()
{
$this->HasMany("App\Models\LoginLogoutLogs");
}
and this is my LoginLogoutLogs Model
public function users()
{
return $this->belongsTo('App\Models\User');
}
I am trying to access name from Users like this
$loginLogoutLogs = LoginLogoutLogs::all();
foreach($loginLogoutLogs as $loginLogoutLog){
dd($loginLogoutLog->users()->name);
}
but i am getting this error
Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$name
EDIT Adding Models
<?php
namespace App\Models;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Zizaco\Entrust\Traits\EntrustUserTrait;
use Session;
use Illuminate\Support\Facades\DB;
class User extends Authenticatable
{
use Notifiable;
use EntrustUserTrait;
protected $table = 'tbl_users';
protected $primaryKey = 'id';
protected $guarded = ['id'];
const API = 'api';
const WEB = 'web';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'last_login', 'Address', 'Age', 'DateOfBirth', 'created_by', 'deleted_by'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'is_admin' => 'boolean',
];
public function isAdmin()
{
return $this->is_admin;
}
static function GetUserNamebyID($id)
{
$name = User::select("name")->where(["id" => $id])->pluck('name');
if (isset($name[0])) {
return $name[0];
} else {
return '';
}
}
public function loginlogout()
{
$this->HasMany("App\Models\LoginLogoutLogs", 'userID');
}
public function company()
{
$this->HasMany("App\Models\Company");
}
}
And now LoginLogouts Model
<?php
namespace App\Models;
use Illuminate\Notifications\Notifiable;
use Zizaco\Entrust\Traits\EntrustUserTrait;
use Illuminate\Database\Eloquent\Model;
use Session;
use Illuminate\Support\Facades\DB;
class LoginLogoutLogs extends Model
{
use Notifiable;
use EntrustUserTrait;
protected $table = 'tbl_users_logs';
protected $primaryKey = 'id';
protected $guarded = ['id'];
const API = 'api';
const WEB = 'web';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'userID','is_accpeted','type','addedFrom'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'is_admin' => 'boolean',
];
public function isAdmin()
{
return $this->is_admin;
}
// change company to hasmany
public function user()
{
return $this->belongsTo('App\Models\User');
}
}
simply change your part of
dd($loginLogoutLog->users()->name);
into
dd($loginLogoutLog->users->name);
remove the bracket on users, its the easy fix.
here we obtain a property, not a function.... (although in the model its defined as function)
Easy fix:
$loginLogoutLogs = LoginLogoutLogs::all();
foreach($loginLogoutLogs as $loginLogoutLog){
dd($loginLogoutLog->users->name);
}
You want to access the relationship entities, as opposed to the relationship model.
By using users(), your code thinks you are trying to call a name() method on the users model, as opposed to your users method on the LoginLogoutLogs class.
You need to change your relationship with user adding the foreign key in LoginLogoutLogs:
public function user()
{
return $this->belongsTo('App\Models\User', 'userID');
}
Also ensure that you call user insted of users
$loginLogoutLogs = LoginLogoutLogs::all();
foreach($loginLogoutLogs as $loginLogoutLog){
dd($loginLogoutLog->user->name);
}
And if you want to perform use eager loading:
$loginLogoutLogs = LoginLogoutLogs::with('user')->get();
foreach($loginLogoutLogs as $loginLogoutLog){
dd($loginLogoutLog->user->name);
}
Remove () when you are getting the child model and add a second parameter to belongsTo.
Here you are:
Migrations:
// Parent migration (create_clients_table):
Schema::create('clients', function (Blueprint $table) {
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
});
// Child migration (create_payments_table):
Schema::create('payments', function (Blueprint $table) {
$table->unsignedBigInteger('client_id');
$table->foreign('client_id')
->references('id')
->on('clients')
->onDelete('cascade');
});
Models relationship:
// Child (Client Model)
public function owner()
{
return $this->belongsTo(User::class, 'user_id');
}
// Parent (User Model)
public function clients()
{
return $this->hasMany(Client::class);
}
Data output:
// Route:
Route::get('/client/{id}/payments', [PaymentController::class, 'paymentsOfClient']);
// In controller (PaymentController):
/**
* Display a listing of the payments of specified Client.
*
* #param string $id
* #return \Illuminate\Http\Response
*/
public function paymentsOfClient($id)
{
$client = Client::find($id);
// check permissions
if (auth()->user()->id !== $client->owner->id) {
return;
}
$payments = $client->payments()->paginate(20);
return response()->json($payments);
}

Trying to get property of non-object in laravel 5.2

this is my posts table
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostsTable extends Migration
{
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->integer('prf_id')->unsigned();
$table->foreign('prf_id')->references('id')->on('profiles')->onDelete('cascade');
$table->longText('status');
$table->timestamps();
});
}
public function down()
{
Schema::drop('posts');
}
}
this my Post model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $table='posts';
protected $fillable = ['status'];
protected $hidden = [];
public function profile(){
return $this->belongsTo('App\Profile');
}
public function user(){
return $this->belongsTo('App\User');
}
}
this is profile model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
protected $table='profiles';
protected $fillable = ['user_id','name','position','roles','username','college','phone','location','graduation','skill'];
protected $hidden = [];
public function posts(){
return $this->hasMany('App\Post');
}
}
this is User model
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
protected $fillable = [
'fname','lname', 'email','sex', 'password','user_id','roles'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function posts(){
return $this->hasMany('App\Post');
}
}
when i try {{$status->user->fname}} this.its show the correct value but when i try {{$status->profile->username}} this ,every time it shows me Trying to get property of non-object (View: C:\xampp\htdocs\abc\resources\views\pages\profile.blade.php)
i really don't know why :(
In your Post class try the following code:
public function profile(){
return $this->belongsTo('App\Profile', 'prf_id');
}

Categories