ERROR : how to get information to foreign key laravel 8 - php

I cannot retrieve the username from the foreign key, please help me.
The user table contains a name field I think with the foreign key I could retrieve that. But it does not work.
My migration table
public function up()
{
Schema::create('bookings', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->integer('doctor_id');
$table->unsignedBigInteger('campagne_id');
$table->string('time');
$table->integer('status')->default(0);
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('campagne_id')->references('id')->on('campagne')->onDelete('cascade');
});
}
My booking Model
public function utilisateur()
{
return $this->belongsTo(User::class, 'user_id', 'id');
}
public function Campagne()
{
return $this->belongsTo(Campagne::class, 'campagne_id', 'id');
}
}
my controller
public function liste()
{
$bookings = DB::table('bookings')->paginate(6);
return view('listeAppointement', compact('bookings', 'doctors'));
}
My erreur enter image description here
i dont know happen. Thanks for advance.

Your setup is good to go, Did you verified that all reference 'user_id' from table bookings exist on users table? It happens sometimes when relation not find required field with foreign key.

Related

Laravel 8: Trying to get property 'name' of non-object

I'm making a forum with Laravel 8. And I want to return a question and show the name of the user who has asked this question.
At the Model User.php I coded this:
public function questions()
{
return $this->hasMany(Question::class);
}
And also I put this at Question.php Model:
public function users()
{
return $this->belongsTo(User::class);
}
So in order to get the name of a user who has asked the question, I put this:
{{ $show->users->name }}
But now I get this error message:
Trying to get property 'name' of non-object**
So what's going wrong here? How can I fix this issue?
Note that this $show variable comes from this Controller Method and gets the question information:
public function showQuestion($slug)
{
$show = Question::where('slug', $slug)->first();
if(is_null($show)){
abort(404);
}
return view('questions.question',[
'show' => $show
]);
}
And also each question has stored the user_id of the user who has asked this question:
So if you have any idea or suggestion on this, please let me know, I would really appreciate that!
Update #1:
Here is the table users:
Update #2:
questions table migration:
Schema::create('questions', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->string('title');
$table->string('slug');
$table->text('body');
$table->string('category');
$table->string('private')->nullable();
$table->timestamps();
});
users table migration:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('phone')->unique();
$table->binary('image')->nullable();
$table->string('job')->nullable();
$table->string('location')->nullable();
$table->string('bio')->nullable();
$table->string('skills')->nullable();
$table->string('stackoverflow')->nullable();
$table->string('github')->nullable();
$table->string('instagram')->nullable();
$table->string('linkedin')->nullable();
$table->string('website')->nullable();
$table->rememberToken();
$table->timestamps();
});
}
Your relationship on Question to User should be named user instead of users. When you are letting Eloquent automatically figure out the fields for the belongsTo relationship it actually uses the name of the relationship method to help determine what the foreign key is.
If you don't want to follow that type of convention with naming the method like that you can explicitly set the foreign key used by the belongsTo method:
public function belongsTo($related, $foreignKey = null, $ownerKey = null, $relation = null)
You have to change the function name users to user in Question model. when you are letting Eloquent automatically figure out the relationship you have to name the function regarding to their relationships like one to one or one to many or many to many.
Try this
public function user()
{
return $this->belongsTo(User::class);
}
{{ $show->user->name }}
Use this for show function in controller
$student= Student::all();
return view('showData',['data' => $student]);
and for view to show data
#foreach($data as $stud)
<tr>
<td>{{$stud)->id}}</td>
<td>{{$stud)->name}}</td>
</tr>
#endforeach
return $this->belongsTo(User::class);
switch to like this, I switched to hasOne and it worked well
return $this->hasOne(User::class, 'id', 'user_id')
->withDefault(['name' => '']);

Laravel - Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails

I am currently learning Laravel through a personal project.
Context
In a blog like application, I need to link an article to its author. When I save the article, I get the error below.
Error
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (parabolica-dev.articles, CONSTRAINT articles_user_id_foreign FOREIGN KEY (user_id) REFERENCES users (id)) (SQL: insert into articles (title, content, excerpt, updated_at, created_at) values (rgergregerg, regergergregerg, regregregregreg, 2020-04-29 09:55:12, 2020-04-29 09:55:12))
Models
Article
class Article extends Model
{
protected $fillable = ['title', 'content', 'excerpt', 'user_id'];
public function user() {
return $this->belongsTo('App\User');
}
}
User
class User extends Authenticatable
{
protected $fillable = [
'name', 'email', 'password',
];
public function article()
{
return $this->hasMany('App\Article');
}
}
Migrations
Users
class CreateUsersTable extends Migration
{
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('users');
}
}
Articles
class CreateArticlesTable extends Migration
{
public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->string('title');
$table->text('excerpt');
$table->text('content');
$table->string('type');
$table->string('status');
// Relationship between article and user
$table->bigInteger('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
});
}
public function down()
{
Schema::dropIfExists('articles');
}
}
Controller
ArticleController
class ArticleController extends Controller
{
public function store(StoreArticle $request)
{
$validatedData = $request->validated();
$user = Auth::user()->id;
$article = Article::create($validatedData);
$article->user_id = $user;
$request->session()->flash('status', 'Article was created!');
return redirect()->route('articles.show', ['article' => $article->id]);
}
}
Solutions tried
Adding user_id to the $fillable array in my Article model, I still get the error.
Adding the nullable() method to user_id in my migration. Saving the article goes through without the error message but the user_id is recorded as null in my table afterwards.
Those are the 2 most proposed solutions across SO / LaravelCasts from what I found. Any suggestions on what I did wrong ?
Thanks for helping me !
The create method creates and saves a new instance of your model. Since the model does not include the users id at that point, it fails.
You could fix that by adding user_id to the fillables array of your model and also add the user id to the $validatedData array before creating the model.
Alternatively, you can also create a new instance of your model with the new keyword, set all data and explicitely save it once you're done:
$article = new Article($validatedData);
$article->user()->associate( Auth::user() );
$article->save();
You have to change this three lines. You insert a row but at the time user_id is null. That's why it shows the error because you assigned the user_id field not nullable.
$article = new Article;
$article->fill($validatedData);
$article->user_id = Auth::user()->id;
$article->save();

Delete all posts related to a user in laravel

this is my posts table
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id');
$table->integer('category_id')->unsigned()->index();
$table->integer('photo_id')->default(0)->unsigned()->index();
$table->string('title');
$table->text('body');
$table->timestamps();
$table->foreign('user_id')
->references('id')->on('users')
->onDelete('cascade');
});
}
this is my users table
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->integer('role_id')->index()->unsigned()->nullable();
$table->integer('photo_id')->index()->default(0);
$table->boolean('is_active')->default(0);
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
these are the relations
public function posts() {
return $this->hasMany('App\Post');
}
public function user() {
return $this->belongsTo('App\User');
}
Delete code of the user
public function destroy($id)
{
$user = User::findOrFail($id);
if($user->photo_id !== 0) {
unlink(public_path() . $user->photo->path);
}
$user->delete();
Session::flash('deleted_user', 'The user has been deleted.');
return redirect('/admin/users');
}
Delete code of the post
public function destroy($id)
{
$post = Post::findOrFail($id);
if($post->photo_id !== 0) {
unlink(public_path() . $post->photo->path);
}
$post->delete();
return redirect('/admin/posts');
}
I am trying to delete all the posts related to a user when I delete a user.
For that, I am using foreign reference constraint in posts table as shown above
But it is not working when I delete the user. The posts are still there.
I dont know what I am doing wrong
This problem occurs most probably because the default table engine in your MySQL instance is set to MyISAM which doesn't support foreign keys. Trying to work with foreign keys on a MyISAM table would definitely not be a bug in Laravel. Although it would be nice if the Schema Builder could automatically set the engine to InnoDB if foreign keys are used.
so, use this line in your schema
$table->engine = 'InnoDB';
or alter the table with
ALTER TABLE table_name ENGINE=InnoDB;
May be help you.
Create you custom method like function destroyAllByUser()
and put the code like
DB::table('posts')->where('user_id', '=', 1)->delete();
I hope it may help
Delete user;
public function destroy($id)
{
$user = User::findOrFail($id);
if($user->photo_id !== 0) {
unlink(public_path() . $user->photo->path);
}
$user->posts->delete();
$user->delete();
Session::flash('deleted_user', 'The user has been deleted.');
return redirect('/admin/users');
}
A alternative way to solve that is to configure database.php file under laravel-project\config folder to work on InnoDB engine.
'mysql' => [
...
'engine' => 'InnoDB'
]
Now you don't need to worry when you using foreign keys...
REMEMBER - If you didn't configured this before you create your tables you should remigrate again.

Laravel saving foreign key in another table

What is the best approach to save the stream_id as a foreign key inside the junk table
I already created the tables both tables.
Migration:
public function up()
{
Schema::table('junk', function(Blueprint $table)
{
$table->integer('stream_id')->after('id')->unsigned();
});
}
Controller function:
public function create(Request $request)
{
// create junk, junk shall contain the stream id as a foreign key (save in database)
$junk = new Junk();
// stream information data -> the data is saved correctly here
$data = $request->all();
$stream = new Stream();
$stream->fill($data);
if($stream->save())
{
return redirect()->route('stream.new')->with('success', 'saved.');
}
else
{
return redirect()->route('stream.new')->with('error', 'not saved.')->withInput();
}
}
My Junk Model:
public function junk()
{
return $this->belongsTo('Stream', 'junk_id');
}
My Stream Model
public function stream()
{
return $this->belongsTo('Junk', 'stream_id');
}
Do you want to use foreign key contraints? If so, You might take this approach. Here is an example of a location table that has a foreign key to the coordinates:
public function up()
{
Schema::enableForeignKeyConstraints();
Schema::create('location', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->uuid('id');
$table->primary('id');
$table->uuid('coordinate_id')->nullable();
$table->string('address')->nullable();
$table->string('city')->nullable();
$table->string('state')->nullable();
$table->string('zipcode')->nullable();
$table->timestamps();
});
Schema::table('location', function(Blueprint $table){
$table->foreign('coordinate_id')->references('id')->on('coordinate');
});
}
There is no reference to the location on the coordinate table.
You should not be assigning $data = $request->all(); you should be using Validator class to protect yourself from mass assignment issues.
It would also be nice to see your Junk class.
If you have the functions to relacionate the models, you can make this:
$junk = new Junk();
$junk->stream()->associate($request->all());
In the relationship:
One to Many, uses the associate() method
Many To Many, uses the attach() method
For more information about the relations in Laravel (Eloquent ORM)
https://laravel.com/docs/5.4/eloquent-relationships#inserting-and-updating-related-models

Laravel one to many relationship results

Hello i am trying to create one to many relationship. One user from user table could have many companies, on other side company could have only one user.
my migration for company table is
public function up()
{
Schema::create('companies', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('address');
$table->string('city');
$table->string('state');
$table->string('contact_person');
$table->string('phone');
$table->string('industry');
$table->string('website');
$table->integer('id_user')->unsigned();
$table->foreign('id_user')->references('id')->on('users')->onUpdate('cascade')->onDelete('cascade');
$table->timestamps();
});
}
my user model is
/**
* Get the posts for the user.
*/
public function companies()
{
return $this->hasOne('App\Company','user_id');
}
my company model is
public function users()
{
return $this->belongsTo('App\User','id');
}
i am trying to get all companies for specific user
try with whereHas but no data in relation object
$results = Company::whereHas('users', function ($query) {
$query->where('users.id',1);
})->get();
Where is my error?
First thing you should change is companies() relation. It has to be hasMany, not hasOne:
public function companies()
{
return $this->hasMany('App\Company');
}
Then get user with all his companies:
$result = User::where('id', $id)->with('companies')->first();
Or, if you want to use Company model like in your example and get only companies:
$result = Company::where('user_id', $id)->get();
Also, you're using id_user in migration. Change it to user_id.

Categories