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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay