Khare's avatar

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:

  1. Upload a file and move it into a directory (this works)
  2. 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?

0 likes
0 replies

Please or to participate in this conversation.