1

Trying to create Fake Posts by using tinker but met with the error code bellow

Illuminate\Database\QueryException with message 'SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (posty.posts, CONSTRAINT posts_user_id_foreign FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE) (SQL: insert into posts (body, user_id, updated_at, created_at) values (Velit deserunt tempore vitae et et aliquid explicabo autem occaecati dolores veritatis accusamus cum natus sint eius laudantium mollitia maxime dolorem eius enim., 2, 2021-04-13 08:42:17, 2021-04-13 08:42:17))'

Below are my codes

PostFactory.php

<?php

namespace Database\Factories;

use App\Models\Post;
use Illuminate\Database\Eloquent\Factories\Factory;

class PostFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Post::class;


    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'body' => $this->faker->sentence(20),
                ];
    }
}

PostController.php

<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;

class PostController extends Controller
{
    public function index(){
        // $posts= Post::get(); //Collect all...
        $posts= Post::paginate(20); //How many you want per page...

        return view('posts.index', [
            'posts' => $posts
        ]);
    }

    public function store(Request $request)
    {
        //dd('ok');
         $this->validate($request, [
             'body' => 'required',
         ]);

        Post::create([
            'user_id' => auth()->id(),
            'body' => $request->body,

        ]);



        return back();
    }
}

Post.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;

    protected $fillable= [
        'body',
        'user_id',
    ];

   /**
     * Get the user that owns the Post
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}
Emmanuel
  • 3
  • 2
  • 6
  • possible duplicate [see here](https://stackoverflow.com/questions/9934387/sqlstate23000-integrity-constraint-violation-with-valid-constraint) – Hassan Malik Apr 13 '21 at 09:32
  • Can you answer these questions so we can help you get the right answer? what command are you running to create the posts? what are the contents of your seeder class? what is you scenario that you want to accomplish? – Ali Ali Apr 13 '21 at 16:35
  • 1. Am using tinker to create fake posts on laravel. 2. App\Models\Post::factory->times(200)->(['user_id' =>2]); 3. public function user() { return $this->belongsTo(User::class, 'user_id', 'id'); } N.B: I also used this in my Post.php protected $fillable= [ 'body', 'user_id', ]; – Emmanuel Apr 13 '21 at 16:53
  • @Emmanuel This means you don't have a user with the id of "2" on your user's table. Either create a user with the id of "2" on your table or you can add a new user with 200 posts by using... User::factory() ->times(1) ->has(Post::factory()->count(200)) ->create(); – Ali Ali Apr 13 '21 at 17:29
  • This is the error I got... Illuminate\Database\QueryException with message 'SQLSTATE[HY000]: General error: 1364 Field 'username' doesn't have a default value (SQL: insert into `users` (`name`, `email`, `email_verified_at`, `password`, `remember_token`, `updated_at`, `created_at`) values (Brett Lebsack, lavonne39@example.org, 2021-04-14 01:31:31, $2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi, QJXf2hSkqX, 2021-04-14 01:31:31, 2021-04-14 01:31:31))' – Emmanuel Apr 14 '21 at 01:32
  • I went to my mysql database and I changed the 'user_id' to nullable, it gave me the error code below Illuminate\Database\QueryException with message 'SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '3' for key 'PRIMARY' (SQL: insert into `posts` (`body`, `id`, `updated_at`, `created_at`) values (Aut illo voluptates et est voluptatem laborum natus et provident quibusdam totam aut dolor qui omnis ea., 3, 2021-04-14 01:53:05, 2021-04-14 01:53:05))' But it updated into my database when I checked it... – Emmanuel Apr 14 '21 at 02:00
  • @AliAli But it updated into my database when I checked it, but it caused another error in my index.blade.php file Attempt to read property "username" on null This is the line where the error code came from '{{ $post->user->username }}' – Emmanuel Apr 14 '21 at 02:14
  • @Emmanuel Wow, wow. let's move to chat to solve this, https://chat.stackoverflow.com/rooms/231105/discussion-between-ali-ali-and-emmanuel – Ali Ali Apr 14 '21 at 08:29
  • @AliAli My reputation is too low to move to chat presently, am currently at 11 and I need 9 more to be able to chat... – Emmanuel Apr 14 '21 at 16:08
  • @Emmanuel, I will try to briefly explain, don't make the username field nullable that's wrong. go to the UserFactory file and add the username field with a fake name. then re-run the seeding. – Ali Ali Apr 14 '21 at 17:44

3 Answers3

1

Cannot add or update a child row: a foreign key constraint fails essentially means that, you are trying to add a row to your posts table for which no matching row (user_id) is present in user table.

akinakalin
  • 66
  • 1
  • I checked my database, and I could see I have a 'user_id' in there, and I also tried the code @nemesiscb but I got the error code above... – Emmanuel Apr 13 '21 at 14:02
  • After reviewing your migration file, you should try to migrate again. This problem may be in the database structure. – akinakalin Apr 14 '21 at 07:01
1

Try to change relationship function in model Post with this:

public function user()
{
    return $this->belongsTo(User::class , 'user_id', 'id');
}

Without this change you are trying to 'connect' Post.id (instead of user_id) with User.id, and Post.id doesn't seem to exist, at least by wath I see from the log.

nemesiscb
  • 11
  • 3
  • I still get the error code below Illuminate\Database\QueryException with message 'SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`posty`.`posts`, CONSTRAINT `posts_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE) (SQL: insert into `posts` (`body`, `user_id`, `updated_at`, `created_at`) values (Velit deserunt libero voluptatem iste nam laudantium sit molestiae non itaque voluptatem voluptatem., 2, 2021-04-13 13:52:28, 2021-04-13 13:52:28))' – Emmanuel Apr 13 '21 at 13:56
  • I think there are some problem in migration/db structure and related models, as said also by @ali-ali: 1. in th insert of users is mentioned 'username' has no defaul value, but in laravel insert you have only 'name; 2. is there an id in users? autoincrement? If you post migrations and/or db structure we can review it without guessing. (try also to remove the costraint if you don't need it) – nemesiscb Apr 14 '21 at 15:39
  • The table was automatically generated by laravel, so I didn't expect it to have issues... But I will be glad if you could advice me more. – Emmanuel Apr 14 '21 at 16:10
  • edit the post adding at least your migration files, Laravel doesn't add costraint on default, something is wrong there – nemesiscb Apr 15 '21 at 07:30
0
  1. The user_id had errors while I was trying to create the fake posts using tkinter because I was assigning to a different user_id.

  2. As @AliAli has said, I had to remove the username from nullable.

Emmanuel
  • 3
  • 2
  • 6