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);
});
- 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
}
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();
});
- 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.
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)