Here I want to show you a possible use of instanceof in polymorphic relationships in Laravel
Remember that with instanceof what we are indicating is to know if the object we are passing is an instance of a particular class in this case books can be post image depending on the theme you are working with.
So here I will first explain the relationship here I have the book one which is the main one as you can see:
class Book extends Model
{
***
public function files()
{
return $this->morphMany(File::class, 'fileable');
}
}
And a book can have c to n files as you can see so it is a one to many type between books and files and files can be books can be images can be anything:
class File extends Model
{
***
protected $fillable = ['file', 'type', 'fileable_type', 'fileable_id'];
public function fileable(): MorphTo
{
return $this->morphTo();
}
}
Here you can see a little bit of what the definition of a file is based on polymorphic relationships in Laravel:
public function fileable(): MorphTo
{
return $this->morphTo();
}
This is important because if we do not receive a file directly, a file that is generic, so to speak, that is to say, at a given moment it is a book, but depending on the record it could be, I don't know, a video, it could be an image, it could be anything. What I mean is that just by receiving a file here I cannot assume that it is a book. I think that is quite clear and I do not want to receive the book here for the reasons mentioned before, because it is supposed to be included here:
if ($file->fileable instanceof Book) {
// TODO
}
What we are downloading according to the theme of this controller that says Book controller we can already assume that this has to be a book, which is what I want to work on here but obviously we have to implement the application so that it is error-free therefore files in the future again can be videos, can be images, can be anything and therefore I want to avoid any problem in which an attacking user or by mistake of mine or whatever can receive here another type of file that is not a book and I remember again that it is a polymorphic relationship of type here in Book we have the files So what I want to get to is that when I go to process this file I want to be completely sure that it is a book so that then the subsequent process does not give me any problem that in this case the subsequent process as we show in the previous code.
- Andrés Cruz
Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter
I agree to receive announcements of interest about this Blog.
!Courses from!
10$
On Udemy
There are 1d 17:07!
!Courses from!
4$
In Academy
View courses!Books from!
1$
See the books