Lab3.3 Many To Many
Lab3.3 Many To Many
md 2024-08-26
Many to Many
To define a many-to-many relationship between the DIARY_ENTRIES and EMOTIONS, you need to set up a
pivot table (DIARY_ENTRY_EMOTIONS).
emotions
1. Run the following command to create the model and migration for the emotions table
Note: The protected $casts property on a model is used to specify how attributes should be cast to
native types when you access them
5. Seed the Emotions Data: create a seeder for the emotions table
This will create a new seeder class called EmotionSeeder in the database/seeders directory.
6. Seed the Emotions Data: Define the Data in the Seeder by opening the newly created
EmotionSeeder.php file located in the database/seeders directory and adding the following codes.
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
Note: Carbon is a date and time library included in Laravel that makes working with dates easier.
2 / 11
Lab5.md 2024-08-26
diary_entry_emotions
1. Run the following command to create the migration for the 'diary_entry_emotions' table
3 / 11
Lab5.md 2024-08-26
Explaination
withPivot('intensity')
Purpose: The withPivot() method is used to specify any additional columns in the pivot table that
you want to access or manipulate when working with the relationship.
Usage: By using withPivot('intensity'), you tell Laravel to retrieve the value of this intensity column
whenever you access the emotions() relationship.
Example: You can retrieve the intensity value associated with a particular emotion for a diary
entry like this:
$diaryEntry = DiaryEntry::find(1);
withTimestamps()
Purpose: The withTimestamps() method is used to automatically handle the created_at and
updated_at columns in the pivot table. This is particularly useful when you want to track when a
relationship was created or last updated.
Usage: By using withTimestamps(), Laravel will automatically set the created_at and updated_at
fields in the pivot table when adding or updating records in the relationship.
When defining a many-to-many relationship in Laravel, the foreign key names in the pivot table can be
left blank because Laravel automatically assumes default naming conventions.
4 / 11
Lab5.md 2024-08-26
Index
The with('emotions') method is used to eager-load the emotions related to each diary entry. This
reduces the number of queries executed and improves performance.
5 / 11
Lab5.md 2024-08-26
if (!empty($validated['emotions']) &&
!empty($validated['intensity'])) {
foreach ($validated['emotions'] as $emotionId) {
$intensity = $validated['intensity'][$emotionId] ?? null;
Explaination:
1. This creates a new DiaryEntry record associated with the currently authenticated user. The
diaryEntries method is an Eloquent relationship that retrieves the diary entries
belonging to the user. The create method then inserts a new record into the diary_entries
table with the validated date and content. (By calling Auth::user()->diaryEntries(),
you’re essentially telling Laravel that you want to create a new DiaryEntry for the user.
Laravel will automatically set the foreign key (user_id) in the DiaryEntry to the ID of the
currently authenticated user.)
2. Check if Emotions and Intensities are Provided: The method first ensures that both
emotions and intensity arrays are not empty.
3. Then attach Emotions to Diary Entry: For each emotionId in the emotions array, it
retrieves the corresponding intensity from the intensity array. The attach method is used
to add records to the pivot table (diary_entry_emotions in this case), associating the
emotionId with the newly created diaryEntry. The intensity value is also saved in the pivot
table. Note: By default, attach inserts a new record into the pivot table. It does not remove
or update existing records.
6 / 11
Lab5.md 2024-08-26
Explaination:
7 / 11
Lab5.md 2024-08-26
In Laravel, when you delete a record from a model that has a many-to-many relationship, you
typically need to ensure that the related pivot table entries are also handled correctly. For the
scenario where deleting a DiaryEntry should also delete its associated entries in the
diary_entry_emotions pivot table, Laravel's default behavior handles this automatically if you have
properly set up the database relationships with cascading delete.
Views
Modify the corresponding Blade views for each of the methods in the DiaryEntryController.
8 / 11
Lab5.md 2024-08-26
9 / 11
Lab5.md 2024-08-26
@error('emotions')
<div class="text-red-500 text-sm mt-2">{{ $message }}</div>
@enderror
</div>
<script>
// Function to toggle the visibility of the intensity input
function toggleIntensityInput(emotionId) {
var checkbox = document.getElementById('emotion_' + emotionId);
var intensityContainer =
document.getElementById('intensity_container_' + emotionId);
10 / 11
Lab5.md 2024-08-26
@error('emotions')
<div class="text-red-500 text-sm mt-2">{{ $message }}</div>
@enderror
</div>
<script>
// Function to toggle the visibility of the intensity input
function toggleIntensityInput(emotionId) {
var checkbox = document.getElementById('emotion_' + emotionId);
var intensityContainer =
document.getElementById('intensity_container_' + emotionId);
document.querySelectorAll('input[type="checkbox"]').forEach(function(checkbo
x) {
toggleIntensityInput(checkbox.value);
});
</script>
Explaination:
1. When you specify $diaryEntry in the form action ({{ route('diary.update', $diaryEntry) }}), you are
passing the specific diaryEntry instance (or its ID) to the named route. For example, it will
generate <form method="POST" action="http://localhost/diary/1">
11 / 11