relationship insert laravel code example

Example 1: laravel how to query belongsTo relationship

$movies = Movie::whereHas('director', function($q) {
    $q->where('name', 'great');
})->get();

Example 2: add the data inside has many relationship laravel

$post = App\Models\Post::find(1);

$comment = $post->comments()->create([
    'message' => 'A new comment.',
]);

--------------- OR ------------------
  
$post->comments()->createMany([
    [
        'message' => 'A new comment.',
    ],
    [
        'message' => 'Another new comment.',
    ],
]);

Tags:

Php Example