Storing a photo in Laravel. Migration file's structure
11,727
you will need to define migrations like these.
In your photo table migration follow this:
Schema::create('photos', function (Blueprint $table) {
$table->increments('id'); //you save this id in other tables
$table->string('title');
$table->string('src');
$table->string('mime_type')->nullable();
$table->string('title')->nullable();
$table->string('alt')->nullable();
$table->text('description')->nullable();
$table->timestamps();
});
FYI the photo's model would look like this:
class Photo extends Model
{
protected $fillable = [
'title',
'src', //the path you uploaded the image
'mime_type'
'description',
'alt',
];
}
In Other table migration:
Schema::table('others', function(Blueprint $table){
$table->foreign('photo_id')->references('id')->on('photos');
});
Other model which has relationship with photo
class Other extends Model
{
public function photo()
{
return $this->belongsTo(Photo::class,'photo_id');
}
}
Comments
-
Mahdi Younesi almost 2 years
I'm creating a table to hold multiple photos a user uploads through a form. I was told to
you'd need to create a separate table for them (photos) create a separate model (Photo with a field 'src')
My issue is with the src. Do i need to save a property of the table as a src so instead of
$table->string('photo);
its
$table->src('photo);
-
Admin about 6 yearsdo i need a src in the advert table. (The one that has a relationship to a photo)
-
Admin about 6 years.What should I do in my controller. I'm already saving an advert through a form, so how should i add the the photo_id to the main table. I get the error when migratting photo_id does not exist in table