<?phpuseIlluminate\Database\Migrations\Migration;useIlluminate\Database\Schema\Blueprint;useIlluminate\Support\Facades\Schema;classCreateCommentsTableextendsMigration{/** * Run the migrations. * * @returnvoid */publicfunctionup() {Schema::create('comments',function (Blueprint $table) { $table->increments('id'); $table->integer('post_id')->unsigned(); $table->string("comment"); $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade'); $table->timestamps(); }); }/** * Reverse the migrations. * * @returnvoid */publicfunctiondown() {Schema::dropIfExists('comments'); }}
C:\xampp\htdocs\songkhoe\app\Models\Post.php
<?phpnamespaceApp\Models;useIlluminate\Database\Eloquent\Factories\HasFactory;useIlluminate\Database\Eloquent\Model;classPostextendsModel{useHasFactory;public $timestamps =false;protected $fillable = ['name' ];/** * Get the comments for the blog post. */publicfunctioncomments() {return$this->hasMany(Comment::class); }}
C:\xampp\htdocs\songkhoe\app\Models\Comment.php
<?phpnamespaceApp\Models;useIlluminate\Database\Eloquent\Factories\HasFactory;useIlluminate\Database\Eloquent\Model;classCommentextendsModel{useHasFactory;protected $fillable = ['post_id','comment' ];/** * Get the post that owns the comment. */publicfunctionpost() {return$this->belongsTo(Post::class,'id'); }}
<?phpnamespaceApp\Http\Controllers;useIlluminate\Http\Request;useApp\Models\Post;useApp\Models\Comment;classTestControllerextendsController{publicfunctionindex($id) { $comments =Post::find($id)->comments;foreach ($comments as $comment) {echo'<pre>';var_export($comment->comment);echo'<pre>'; } }publicfunctionindex2($id) { $post =Comment::find($id)->post;echo'<pre>';echo"id and name => ". $post->id ." and ". $post->name;echo'<pre>'; }}
C:\xampp\htdocs\songkhoe\routes\web.php
<?phpuseIlluminate\Support\Facades\Route;useApp\Http\Controllers\TestController;/*|--------------------------------------------------------------------------| Web Routes|--------------------------------------------------------------------------|| Here is where you can register web routes for your application. These| routes are loaded by the RouteServiceProvider within a group which| contains the "web" middleware group. Now create something great!|*/Route::get('/',function () {returnview('welcome');});Route::get('/test/{id}', [TestController::class,'index']);Route::get('/test2/{id}', [TestController::class,'index2']);Route::get('/save/{id}', [TestController::class,'save']);
In a relational database management system, we know database tables are related to one another. For example, a post may have many comments or an order could be related to the user who placed it. Laravel eloquent makes managing and working with these relationships very convenient. Laravel provides many relationships and in this tutorial, I will show you how we handle one to many or we can call this hasMany eloquent relationship.
In this Laravel 9 one to many relationship example tutorial, I am going to use the Post and Comments concept. Suppose, A post may have many comments and a comment may be related to one post. Let's see how we can define Laravel's one to many relationship.
We can use the hasMany() method to define one to many relationships and the first argument passed to the hasMany method is the name of the related model class. In this example, I will create a posts table and a comments table. Now I will create one to many relationships with each other by using the Laravel Eloquent Model.
Our table is ready, now we can define one to many or hasmany eloquent relationship by the following way:
app\Models\Post.php
<?phpnamespaceApp\Models;useIlluminate\Database\Eloquent\Model;classPostextendsModel{/** * Get the comments for the blog post. */publicfunctioncomments() {return$this->hasMany(Comment::class); }}
PHPCopy
If we avoid foreign like above, then remember Laravel Eloquent will assume the foreign key column on the Comment model is post_id. Now we can find every comment of a single post like:
App\Http\Controllers\TestController.php
<?phpnamespaceApp\Http\Controllers;useApp\Models\Post;useIlluminate\Http\Request;classTestControllerextendsController{publicfunctionindex($id) { $comments =Post::find($id)->comments;foreach ($comments as $comment) {// } }}
PHPCopy
Defining Inverse Relationship of hasMany
Now we know how to define hasMany or one to many relationships. Now we will see how we can define the inverse relationship of hasMany. Let's define a relationship on the Comment model that will let us access the post. We can define the inverse of a hasMany relationship using the belongsTo method like:
app/Models/Comment.php
<?phpnamespaceApp\Models;useIlluminate\Database\Eloquent\Model;classCommentextendsModel{/** * Get the post that owns the comment. */publicfunctionpost() {return$this->belongsTo(Post::class); }}
Here we can also pass fereign_key and local_key like below:
<?phpnamespaceApp\Models;useIlluminate\Database\Eloquent\Model;classCommentextendsModel{/** * Get the post that owns the comment. */publicfunctionpost() {return$this->belongsTo(Post::class,'foreign_key','owner_key'); }}