Atakan
Atakan

Reputation: 91

Creating A Data Record For a One-to-Many Category Structure With Laravel

I'm new here. With Laravel, I want to save data with multiple selection features. however, the methods in the model file I created do not appear.I'm new to larvae, how can I fix it? I couldn't run the multiple-selection feature.

Method in controller

public function saveForm()
{
    $movi_name = $req->input('movi_name');
    $release_date = $req->input('release_date');

    $data = array(
        'movi_name'    => $movi_name,
        'release_date' => $release_date
    );

    $categories = request(categories);

    $entry = Movie::insert($data) /*Model File and Save Data*/

    $entry->categories()->attach($categories);
}

Method in my model file

protected $table = 'film';

public function categories()
{
    return $this->belongsToMany('App\Models\Kategori', 'category_movie');   
}

it should be that the selected films have to be included in the categories.. But

call to member function categories() on boolean

Sorry for bad English

Upvotes: 0

Views: 29

Answers (2)

Atakan
Atakan

Reputation: 91

yes I solved the problem

protected $fillable = ['movie_name'];

that was my code.

now that

protected $fillable = ['movie_name','release_date'];

Upvotes: 0

Rwd
Rwd

Reputation: 35200

As mentioned in the comments you should use create() instead of insert().

Using insert() will simply return true or false depending on whether the query was successful or not.

Using create() will return an instance of Movie model which will have the categories() method on it:

$entry = Movie::create($data); //<--This is where insert() is replaced with create()

$entry->categories()->attach($categories);

You will need to make sure that movi_name and release_date are in the $fillable array in your Movie model:

protected $fillable = ['movi_name', 'release_date'];

Upvotes: 1

Related Questions