How to retrieve the media of a related model with Laravel Medialibrary? - laravel-5

I have an Album model and Track model. They have OneToMany relationship. An Album can have many tracks and a track can only belong to one Album. I'm using media library to associate the files of a song which is the cover and the mp3 to a Track model.
In my AlbumController, I have a query like this;
$album = $album->where('id', $id)->with('tracks', 'artist')->first();
return view('admins.albums.show', compact('album'));
This loads the tracks of the album but not the media. In my views, I can get the media by looping through the tracks and calling the getMedia() function but what about for Api?
How can I return the media as a Json before it is sent as a response?

You can use an ancestor (https://laravel.com/docs/5.8/eloquent-mutators#accessors-and-mutators) to append the url to the model, for example (im using a diferent model btw):
place this first in the beginning of the model (it doesnt matter):
protected $appends = [
'logo_url'
];
and them:
public function getLogoUrlAttribute()
{
return (empty($this->getMedia('restaurants')[0])) ? "" : $this->getMedia('restaurants')[0]->getFullUrl();
}
this code goes on the model that has the media trait attached to it.

Related

Laravel Mongodb Getting Data from the same collection but has different type

I am trying to make a VOD and Aduio Streaming platform and I am using Laravel 9 and Mongodb as a database.
I have one collection that has all the media in it wether it's an audio or a video, what's seperating them for me is an attribute called "type", and it has an enum of 'audio' or 'video'. I have one model called Media which can access both aduio and Video, and I would like to make an Audio Model that can access only the media who has type 'audio'.
Is there any way to apply filter while using the same collection? Or do I need to create another collection to be able to acheive that?
Thanks in advance
Yes, it's possible using the eloquent's query scope feature.
As you mentioned, you already have a "Media" model from which you can access both Audio and Video.
Now you want to create an "Audio" model which will only access the media of type audio. i.e. type = 'audio'
Here is how you can do it.
class Audio extends Model
{
// All other stuff in model
/**
* The "booted" method of the model.
*
* #return void
*/
protected static function booted()
{
static::addGlobalScope('audio', function (Builder $builder) {
$builder->where('type', 'audio');
});
}
}
Global scopes allow you to add constraints to all queries for a given model.
After adding the scope in the example above to the App\Models\Audio model, a call to the Audio::all() method will execute the following SQL query:
select * from `medias` where `type` = 'audio'

Is this a valid use case for a One To Many polymorphic eloquent?

I have the following models, Property, Building and Unit.
The relations between Property and Building are following:
class Property extends Model
{
public function building(){
return $this->belongsTo('App\Building');
}
}
and the Building model is like this.
class Building extends Model
{
public function properties(){
return $this->hasMany('App\Property');
}
}
In words, each property has one Building, and what I need is, that Each building of the specific property has its own Units. Buildings can have many Units.
no, this situation is not a good use case for polymorphic relationships. let's say we have an album with music in it, so we have an albums_table and music_table. in our situation, users should be able to like or dislike both albums or music separately, so we create a like_table and make a polymorphic relation between music and albums. I think this example would help you.

how to display the current logged on users picture from a relationship laravel

I want to retrieve the user's photo and display it in a thumbnail form which i have stored in public/assets/uploads/thumbnail/. I tried auth()->user()->user_detail->file_name but I can't get it to work. How do you do it ?
you have to first define a relationship if they are stored in different table
like i did in model
public function imagedata() {
return $this->hasMany(Images::class, 'listID', 'id');
}
and after that when you get the user just call this method like this
$listingimg = Listings::findOrfail($id);
and for calling the relationship
foreach (listingimg as $singleIlisting) {
$singleIlisting->imagedata;
}
modify the code according your needs as if needed and by the way relatio is one to many

Using eloquent in laravel to join third table. Best way to accomplish?

I am trying to join all videos for a given track along with joining the make and model from the vehicles table. Each video contains only one Vehicle from the vehicles table. I am having difficulties using Eloquent syntax on how I can make this happen.
The Track model i built to grab all the videos is very straight forward and works well as written below:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Track extends Model
{
public function video()
{
return $this->hasMany('App\Video');
}
}
I've written by Vehicles model as below:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Video extends Model
{
function vehicle()
{
return $this->hasOne('App\Vehicle');
}
}
The three database models look like the following
tracks
id
name
city
state
url_key
videos
id
youtube_id
date
best_lap_time
vehicles_id
vehicles
id
make
model
The below answer assumes your video() relation works well (as you said). But looking at your database schema and models, you don't have a column named track_id in your videos table, so I'm not sure about that.
Your vehicle relationship should look like this (you defined the inverse):
function vehicle()
{
return $this->belongsTo('App\Vehicle', 'vehicles_id');
}
Then your query should look something like this:
$result = \App\Track::with('video.vehicle')->get()

Adding data to an eloquent collection?

Im getting various data out of my database.
Product::with('users');
I also have toe execute a complex raw query to get back some information. This is returned as an array.
In my method I would like to get products with users and then add on the data from my raw query to this collection, but this data comes back as an array. Something like:
Product::with('users');
Product->extraData = $rawQuery;
How can I add the raw query output to my Product Collection?
By using Eloquent Facade like Product:: you will get an Eloquent Model object as a result or an Eloquent Collection object as a result, including results retrieved via the get method or accessed via a relationship.
Now, if i understand correctly, you need to add a single extraData property to Eloquent Collection model alongside with Collection items? Or you need to add extraData for each Product ?
If you need to add additional property to Eloquent Collection object, maybe it is a good idea to use a Custom Collection. Please read this section: http://laravel.com/docs/5.1/eloquent-collections#custom-collections .
<?php namespace App;
use App\CollectionWithExtraData;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function newCollection(array $models = [])
{
return new CollectionWithExtraData($models);
}
}
And maybe your CollectionWithExtraData can have let's say a
public function setExtraData() {
}
or
public $extraData = array();
If you need extraData for each Product Eloquent Model, just create a new attribute within your Eloquent Model, make it public and set your extra data when needed. Make use of setExtraData() method and $extraData property from above

Resources