What is the issue? What happens in to your code? Did you set your routes?
Sep 27, 2019
3
Level 2
Working with API
I am trying to create api using laravel to work on vuejs, i am trying to get a album using the ID also list of songs associated with the album.
url sample http://localhost:8080/album/5
Album Resource
public function toArray($request)
{
return [
'albumDetails' => [
'id' => $this->id,
'title' => $this->title,
'artworkPath' => $this->artwork_path,
'albumdate' => $this->album_date,
'upc' => $this->upc,
'recordlabel' => $this->record_label,
],
'artistId' => [
'id' => $this->artist->id,
'artistName' => $this->artist->name,
],
'artistName' => [
'id' => $this->artist->id,
'artistName' => $this->artist->name,
],
'genre' => [
'id' => $this->genre->id,
'genre' => $this->genre->name,
],
];
}
Album Model
class Album extends Model
{
public function artist()
{
return $this->belongsTo(Artist::class);
}
public function genre()
{
return $this->belongsTo('App\Genre');
}
}
Album Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Album;
use App\Http\Resources\Album as AlbumResource;
class AlbumController extends Controller
{
public function index()
{
// Get albums
$albums = Album::with('artist')->orderBy('artist_id', 'desc')->limit(8)->get();
// Return collection of albums as a resource
return AlbumResource::collection($albums);
}
public function store(Request $request)
{
$album = new Album();
$album->title = $request->input('title');
$album->artist_id = $request->input('artist_id');
$album->genre_id = $request->input('genre_id');
$album->artwork_path = $request->input('artwork_path');
$album->album_date = $request->input('album_date');
$album->upc = $request->input('upc');
$album->record_label = $request->input('record_label');
if($album->save()) {
return new AlbumResource($album);
}else{
return "Error Saving";
}
}
public function show($id)
{
// Get single album
$album = Album::findOrFail($id);
// Return single album as a resource
return new AlbumResource($album);
}
public function destroy($id)
{
// Get single album
$album = Album::findOrFail($id);
if($album->delete()) {
return "deleted";
}else{
return "Error Deleting";
}
}
}
Album Vuejs
<script>
import axios from 'axios';
export default {
name: 'album',
props:['id'],
data: function(){
return {
person: null
}
},
methods: {
getData(){
var that = this
axios.get('http://api.localhost/api/album/'+this.id)
.then(function (response){
that.person = response.data.data;
})
}
},
mounted: function(){
this.getData()
}
}
</script>
Please or to participate in this conversation.