Most ORMs generally have methods that allow for creating relationships between database tables. Laravel is no exception. In this tutorial, we are going to go over creating One-Many Relationships using Laravel Eloquent. We’ll use our User Model and JWT project from our previous tutorial as a starting point. Click here to gain access to our video courses on Laravel, JWT as well as Front-End Frameworks such as VueJS and React.
Adding Our Eloquent One-Many Relationship
This first thing that we’ll have to do is add our Eloquent model and its respective migration file. This can be done in one simple command.
php artisan make:model Post --migration
Inside of the migration file, add your columns as well the foreign key to set up the relationship.
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('body');
$table->timestamps();
$table->integer('user_id');
});
The last step will be to add methods on your models that specify that they are associated with another model. Inside your User Model, add a method that will show that a User has many Posts. Also inside your Posts Model at a method showing it belongs to a User.
class User extends Authenticatable
{
use HasApiTokens, 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',
];
public function posts()
{
return $this->hasMany('App\Post');
}
}
class Post extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'title', 'body',
];
public function user()
{
return $this->belongsTo('App\User');
}
}
Creating the Post API Controller
The next step will be to create our controller. Run the following command in your terminal.
php artisan make:controller API/PostController --api
Now inside of your controller methods, create your basic CRUD statements with the exception of using the Auth::user in each statement.
<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Post;
use App\User;
use Illuminate\Support\Facades\Auth;
use Validator;
class PostController extends Controller
{
public $successStatus = 200;
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
$user = Auth::user();
$posts = $user->posts;
return response()->json(['posts' => $posts], $this-> successStatus);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$user = Auth::user();
$post = $user->posts()->create($request->all());
$user->posts()->save($post);
return response()->json(['post' => $post], $this-> successStatus);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$user = Auth::user();
$post = $user->posts()->find($id);
return response()->json(['post' => $post], $this-> successStatus);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$user = Auth::user();
$post = $user->posts()->findOrFail($id);
$post->update($request->all());
return response()->json(['post' => $post], $this-> successStatus);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$user = Auth::user();
$user->posts()->find($id)->delete();
return response()->json(['post' => []], 204);
}
}
Inside of your api.php route file, add the api resource to your routes.
Route::group(['middleware' => 'auth:api'], function(){
Route::post('details', 'API\UserController@details');
Route::post('logout', 'API\UserController@logout');
Route::resource('posts', 'API\PostController');
});
Now when you run your application, you’ll be able to limit the posts that you create and delete based on the logged in user.

Laravel Get ALL Posts

Laravel Create Posts
Conclusion
Building out Eloquent Models that use relationships is fairly easy. In the next tutorial, we’ll go over One-One relationships with Laravel Eloquent. Click here to gain access to more tutorials and videos or click bellow subscribe to our blog.
Codebrains Newsletter
Get weekly dev news and tutorials.
About The Author: James Coonce
James Coonce is a programmer from Tampa Fl that has a love for golf, travel and language learning. When he's not hitting golf balls, he's probably watching foreign movies.
More posts by James Coonce