DEV Community

Cover image for How to delete data from one to one relationship in Laravel?
Mahmoud Adel
Mahmoud Adel

Posted on • Originally published at laravelspa.site on

How to delete data from one to one relationship in Laravel?

Delete data using User Model.

  • We first go to the routes/web.php file and add this route:
Route::get('/users/profile/delete', method () {
    $user = User::with('profile')->find(1);
    $user->profile()->delete();
    return response()->json($user);
});
Enter fullscreen mode Exit fullscreen mode
  • We open the browser and navigate to the new URL http://127.0.0.1:8000/users/profile/delete to find that the profile have been deleted successfully.
{
  "id": 1,
  "username": "Joun Doe",
  "created_at": "2023-08-07T06:23:03.000000Z",
  "updated_at": "2023-08-10T05:07:38.000000Z",
  "profile": null
}
Enter fullscreen mode Exit fullscreen mode

Refresh the page twice to show that this user's profile has been deleted.

Delete data Using Profile Model.

  • We first go to the routes/web.php file and add this route:
Route::get('/profiles/user/delete', method () {
    $profile = Profile::with('user')->findOrFail(2);
    $profile->delete();
    $profile->user()->delete();
});
Enter fullscreen mode Exit fullscreen mode
  • We open the browser and navigate to the new URL http://127.0.0.1:8000/profiles/user/delete. We see that both the user and the profile have been deleted successfully. Rcord has deleted

Conclusion

This article is the start of a whole series on Laravel Eloquent Relationships - Relationships within Laravel. We have covered the One TO One relationship in a complete way. We did not spare you any information, and God willing, in the following explanation, we will learn about the One To Many relationship.

  • You can find the repo of this series on github here

Top comments (0)