How to delete data from one to one relationship in Laravel?
·208 words·1 min·
0
·
0
·
Laravel
Laravel Relationships
laravel10
eloquent
relationships
Table of Contents
Laravel Eloquent Relationships - This article is part of a series.
Part 6: This Article
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:
laravelspa/laravel-relations
PHP
0
0
Laravel Eloquent Relationships - This article is part of a series.
Part 6: This Article
Related
How to update a one-to-one relationship in Laravel?
·449 words·3 mins·
0
·
0
Laravel
Laravel Relationships
laravel10
eloquent
relationships
How can you retrieve data from a one-to-one relationship in Laravel?
·1980 words·10 mins·
0
·
0
Laravel
Laravel Relationships
laravel10
eloquent
relationships
How to insert data in one to one relationship in database?
·435 words·3 mins·
0
·
0
Laravel
Laravel Relationships
laravel10
eloquent
relationships