Friday, March 31, 2017

Argument 1 passed to Illuminate\Database\Eloquent\Relations\BelongsToMany::formatRecordsList() must be of the type array, null given

I'm getting this error on Laravel 5.4. I'm creating tags for my blog but the only thing I get is an error.

public function category()
{
    return $this->belongsTo('gamstec\Category');
}

public function tags()
{
    return $this->belongsToMany('gamstec\Tag');
}

This is my Tag Model:

public function Posts()
{
    return $this->belongsToMany('gamstec\Post');
}

Now this is my PostController.php:

public function create()
{
    $categories = Category::all();
    $tags = Tag::all();
    return view('posts.create')->withCategories($categories)->withTags($tags);
}

The store Functions:

public function store(Request $request)
{

    // validate the data
    $this->validate($request, array(
    'title'         =>      'required|max:255',
    'slug'          =>      'required|alpha_dash|min:5|max:255|unique:posts,slug',
    'body'          =>      'required',
    'stickers'      =>      'required|min:1|max:20',
    'category_id'   =>      'required|integer',
    'postimg'       =>      'required'
));

    // store in database
    $post = new Post;

    $post->title        =       $request->title;
    $post->slug         =       $request->slug;
    $post->body         =       $request->body;
    $post->stickers     =       $request->stickers;
    $post->category_id  =       $request->category_id;
    $tags               =       $request->input('tags', []);
    $post->postimg      =       $request->postimg;

    $post->save();

    $post->tags()->sync($request->tags, false);

    Session::flash('success', 'La publicación se ha creado correctamente');

    // redirect to another page
    return redirect()->route('posts.show', $post->id);
}

This is the Tags crate form:

I'd tryied removing

$tags =  $request->input('tags', []);

and the same error.

This is my Tags Crete select form:






<select class="form-control select2-multi" name="tags[]" multiple="multiple">




@foreach($tags as $tag)




<option value=''></option>



@endforeach



</select>

so on select form i put the name="tags[]" with an empty array to pass the data into an array but still not working.



via Juan Rincón

Advertisement