May 8, 2016
0
Level 7
Uploading Image file with Dropzone results in Call to a member function create() on null
Hello,
Having some trouble with uploading a photo and referencing a relationship between two models in my project. One category can have many photos. I am trying to:
- Upload a file and move it into a directory (this works)
- Relate the uploaded file to a model using hasMany relationship
When the method triggers the upload works but the second part fails and results in an error: "Call to a member function create() on null"
The Category model: class Category extends Model { protected $table = 'categories';
protected $fillable = [
'name', 'description',
];
public function photos ()
{
$this->hasMany('App\CategoryPhoto');
}
}
The CategoryPhoto Model: class CategoryPhoto extends Model {
protected $table = 'category_photos';
protected $fillable = ['photo'];
public function category ()
{
$this->belongsTo('App\Category');
}
}
The AddPhoto method on the CategoryController: public function addPhoto (Request $request, $id) { $file = $request->file('file');
$name = time() . $file->getClientOriginalName();
$file->move('categories/photos', $name);
$category = Category::findOrFail($id);
$category->photos()->create(["photo" => "/categories/photos/{$name}"]);
}
Any ideas?
Please or to participate in this conversation.