0

I'm learning laravel and writing a simple project while learning it, but there is a problem that I couldn't solve. I have a form which is for creating an article like this :

<form action="{{route('admin.article.store')}}" method="POST">
@csrf
        
        //some divs

        <div class="form-group">
        <label for="title">Category</label>
        <div id="output"></div>
        <select class="chosen-select" name="categories[]" multiple style="width:400px">
          @foreach ($categories as $cat_name => $cat_id)
          <option value="{{$cat_id}}">{{$cat_name}}</option>
          @endforeach
        </select>
        </div>

        <div class="form-group">
            <label for="title"></label>
            <button type="submit" class="btn btn-inverse-success btn-fw">Create</button>
            <a href="{{route('admin.article.index')}}" class="btn btn-inverse-warning btn-fw">back</a>
        </div>

</form>

And in my controller, I'm storing this requests like this :

$article = $article->create($request->all());
$article->categories()->attach($request->$categories);

but after testing, it says:

ErrorException

Undefined variable: categories

what can I do?

2
  • You have not defined $categories, you are using on your foreach loop. Post your controller code, and probably index function. Commented Jun 21, 2020 at 11:13
  • no, the view is ok, the foreach loops correctly and displays the categories, but the problem is when I try to save (store) the form Commented Jun 21, 2020 at 11:17

1 Answer 1

2

It's a typo mistake. You are using $request->$categories, should be $request->categories. Remove the extra dollar ($) sign.

$article->categories()->attach($request->categories); 
Sign up to request clarification or add additional context in comments.

1 Comment

Oh thank you, I've been searching for typo but not this type, sorry

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.