Trying to get property of non-object in laravel 5.2 - php

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');
}

Related

how to remove children data in case many to many relationship in laravel by using observer?

there is a (card model) bleongsToMany contacts, and there is a (contact model) is bleongsToMany cards, I want when (card) get updated his children in the middle table in the relation became removed.
I'm trying to do this by using (the observer), I did all steps correctly but the issue is:
when (card model) updated his children still exist in the middle table of the relationship, I want to remove them when any update on the card.
Route:
Route::get('/test',function(){
$card = \App\Models\Card::find(1);
$card-> update([
'name' => 'firstCard1',
'user_name' =>1,
]);
return true;
});
Observer:
<?php
namespace App\Observers;
use App\Models\Card;
class CardObserver
{
public function updated(Card $card)
{
$card -> contact()-> delete();
}
}
Card Model:
<?php
namespace App\Models;
use App\Observers\CardObserver;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Card extends Model
{
use HasFactory;
protected $fillable = [
'name',
'user_id ',
];
public $timestamps = true;
protected $hidden = ['pivot'];
public function contact()
{
return $this->belongsToMany(Contact::class, 'card_contacts', 'card_id');
}
public function connection()
{
return $this->belongsTo(Connection::class, '');
}
protected static function boot()
{
parent::boot();
Card::observe(CardObserver::class);
}
}
Contact Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Contact extends Model
{
use HasFactory;
protected $fillable = [
'provider_id',
'user_id',
'contact_string'
];
public $timestamps = true;
protected $hidden = ['pivot'];
public function card(){
return $this->belongsToMany(Card::class,'card_contacts','contact_id');
}
public function user(){
return $this->belongsTo(User::class,'user_id');
}
public function provider(){
return $this->belongsTo(Provider::class,'provider_id');
}
}
Card_contact Model (the pivot table):
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class CardContact extends Model
{
use HasFactory;
protected $fillable = [
'card_id',
'contact_id',
];
public $timestamps = true;
}
any help please?

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();
}

How can i get data using Eloquent Relationships in laravel

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;
}
}

how do i go getting this eloquent relationship right?

I have an user model and a student model which I have created relationship for, but when I try to
$student->user->fullname
I get this error
"trying to get property fullname of non-object"
here is my user model code:
<?php
namespace App;
use App\Assignment;
use App\Model\Quiz;
use App\Model\Course;
use App\Topic;
use App\Model\Guardian;
use App\Model\Student;
use App\Model\Teacher;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable implements MustVerifyEmail
{
use Notifiable, HasRoles, SoftDeletes;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'fullname',
'email',
'avatar',
'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 setPasswordAttribute($password)
{
$this->attributes['password'] = bcrypt($password);
}
public function guardian()
{
return $this->belongsTo(Guardian::class);
}
public function teacher()
{
return $this->belongsTo(Teacher::class);
}
public function student()
{
return $this->belongsTo(Student::class);
}
public function assignments()
{
return $this->hasMany(Assignment::class);
}
public function quizzes()
{
return $this->hasMany(Quiz::class);
}
public function courses()
{
return $this->hasMany(Course::class);
}
public function topics()
{
return $this->hasMany(Topic::class);
}
public function levels()
{
return $this->hasMany(Level::class);
}
}
and here is my student model code
<?php
namespace App\Model;
use App\User;
use App\Model\Course;
use App\Assignment;
use App\Level;
use App\Model\DoneQuiz;
use App\Model\Teacher;
use App\Model\Guardian;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
protected $fillable = ['user_id', 'level_id', 'guardian_id'];
public function user()
{
return $this->belongsTo(User::class);
}
public function courses()
{
return $this->hasMany(Course::class);
}
public function assignments()
{
return $this->hasMany(Assignment::class);
}
public function level()
{
return $this->hasOne(Level::class);
}
public function teachers()
{
return $this->hasMany(Teacher::class);
}
public function guardian()
{
return $this->hasOne(Guardian::class);
}
public function donequizzes()
{
return $this->hasMany(DoneQuiz::class);
}
}
and even when I try to use this relationship to get data like
'student_id' => auth()->user()->student()->id
I get this error
"BadMethodCallException Call to undefined method
Illuminate\Database\Eloquent\Relations\BelongsTo::id()"
when you use student() it returns a query builder
Either change it to simple student
'student_id' => auth()->user()->student->id
OR
'student_id' => auth()->user()->student()->first()->id

How to delete posts of user at delete account?

I just made a delete function of accounts, but I'm stuck on a problem.I need to also delete posts of user, at delete account.How can I make that? I have table Users, where I have all details from users, and table Posts, where also have user_id and id,caption and image of post.
public function delete($id)
public function delete($id)
{
$profile = User::find($id);
$profile->delete();
Session::flash('remove', "The profile was successfully deleted!");
return redirect('login');
}
Profile.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
protected $guarded = [];
public function profileImage(){
$imagePath = ($this->image) ? $this->image : 'profile/vx2k9TEhkcgaRdOWKvs4lsxqOVmuzwumtwySEnvH.png';
return '' . $imagePath;
}
public function user(){
return $this->belongsTo(User::class);
}
public function followers(){
return $this->belongsToMany(User::class);
}
}
User.php
<?php
namespace App;
use App\Mail\NewUserWelcomeMail;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Mail;
use Actuallymab\LaravelComment\CanComment;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'username', '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',
];
protected static function boot()
{
parent::boot();
static::created(function ($user) {
$user->profile()->create([
'title' => $user->username,
]);
});
}
public function posts()
{
return $this->hasMany(Post::class)->orderBy('created_at', 'DESC');
}
public function profile()
{
return $this->hasOne(Profile::class);
}
}
Post.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $guarded = [];
public function user(){
return $this->belongsTo(User::class);
}
public function likes()
{
return $this->hasMany('App\Like');
}
public function comments()
{
return $this->hasMany('App\Comment');
}
public function tags()
{
return $this->belongsToMany('App\Tag');
}
}
Migration posts table
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->string('caption');
$table->string('image');
$table->timestamps();
$table->index('user_id');
});
}
I think you could try to delete related model in the controller before the user, i.e.:
public function delete($id)
{
$profile = User::find($id);
$profile->posts()->delete();
$profile->delete();
Session::flash('remove', "The profile was successfully deleted!");
return redirect('login');
}
Or you can go with model event, i.e.:
protected static function boot() {
parent::boot();
static::created(function ($user) {
$user->profile()->create([
'title' => $user->username,
]);
});
static::deleting(function($user) {
$user->posts()->delete();
});
}

Categories