Clicking on "show tracks" will show a popup with the tracks of the album
The tracks are not stored in the database, but are retrieved from the MusicBrainz API(opens new window)
where the attribute mb_id in our database is the unique key of the album
E.g. the album Rumours by Fleetwood Mac has the mb_id value 081ea37e-db59-4332-8cd2-ad020cb93af6
Line 10: create a public method showTracks that takes the id of the selected record as a parameter $record
Line 12: store the parameter $record in the public property $selectedRecord
Line 13: (temporary) dump the property $selectedRecord to the page
classShopextendsComponent{useWithPagination;// public propertiespublic$perPage=6;public$loading='Please wait...';public$selectedRecord;publicfunctionshowTracks($record){$this->selectedRecord=$record;dump($this->selectedRecord);}publicfunctionrender(){...}}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
And, as expected, when we click on the album Rumours by Fleetwood Mac the property $selectedRecord contains only the id of the record (id is 5)
Instead of only the id we want to store the complete record in the public property $selectedRecord
The long way is to query the database for the record with the id and store the result in the public property $selectedRecord
But there is a better way: we can use Laravel's Route Model Binding(opens new window) to get the complete record with only the id as a parameter in the method showTracks
Line 1: type-hint the parameter $record with the model Record => replace showTracks($record) with showTracks(Record $record)
Line 4: dump the property $selectedRecord as an array to the page (add ->toArray())
Line 4: the URL which contains the mb_id of the selected record
Line 5: $response fetches the URL with the Laravel HTTP client (include use Http;) and convert the result to JSON data
($response contains all the data from the API, like we can see in the first screenshot of this chapter)
Line 6:
push a new key tracks to the selected record $this->selectedRecord['tracks']
select only the tracks-array in the response ($response['media'][0]['tracks']) and add them to the tracks key
Line 7: (temporary) dump and die the selected record, with the tracks, to the page
createFromTimestampMs creates a Carbon object from a timestamp in $milliseconds
format formats the Carbon object to a string
Line 6: wrap the length of the song in a Carbon object
IMPORTANT
Because there is no Blade helper for Carbon, we need to use the full namespace for the class Carbon\Carbon::createFromTimestampMs($milliseconds)->format('i:s')
Another option is to use the use statement at the top of the file: @php use Carbon\Carbon; @endphp and then use Carbon::createFromTimestampMs($milliseconds)->format('i:s') in the view