简体   繁体   中英

Getting “Undefined variable: categories” error in laravel

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?

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

$article->categories()->attach($request->categories); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM