Hi, I am trying to find an easy way of assigning an image to the article.
I am able of successfully creating an article and uploading the data onto the database as well as uploading an image and moving it into the public folder.
However I am stuck as I still cannot figure out how to assign the image onto the article after researching it.
Heres the code:
Article Model
class Article extends Model
{
// Protecting from the mass assignment...
protected $fillable = [
'title',
'type',
'body',
'published_at'
];
// A single article is owned by a user...
public function user()
{
return $this->belongsTo('App\User');
}
// A single article can have one image...
public function image()
{
return $this->hasOne('App\Image');
}
Article Controller
// Store the article...
public function store(ArticleRequest $request)
{
$article = new Article($request->all());
// Assign the user id to the created article...
Auth::user()->articles()->save($article);
Article Migration
public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('image_id')->unsigned();
$table->string('title');
$table->string('type');
$table->text('body');
$table->timestamps();
$table->timestamp('published_at');
$table->foreign('user_id')
->references('id')
->on('users');
});
}
Image model
class Image extends Model
{
// Protecting from the mass assignment...
protected $table = 'images';
protected $fillable = [
'title',
'description',
'image'
];
// An image blongs to a single article
public function article()
{
return $this->belongsTo('App\Article');
}
Image Controller
public function upload()
{
return view('/admin/media/imageupload');
}
public function store(Request $request)
{
$image = new Image();
$this->validate($request, [
'title' => 'required',
'image' => 'required'
]);
$image->title = $request->title;
$image->description = $request->description;
if($request->hasFile('image')) {
$file = Input::file('image');
$name = time(). '-' .$file->getClientOriginalName();
$image->filePath = $name;
$file->move(public_path().'/uploads/', $name);
}
$image->save();
}
Image Migration
public function up()
{
Schema::create('images', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('description');
$table->string('filePath');
$table->timestamps();
});
}