I
I
Ilya Loopashko2021-04-30 05:36:54
Laravel
Ilya Loopashko, 2021-04-30 05:36:54

How to pass input names to an array?

Kind everyone. I have a form, I want to pass the names of the inputs in an array instead of name="title" pass name="pass[title]", and then, in order not to cry many lines of code in the controller, replace everything with one line. I ran into a problem, how do I pass $pass->user_id = $id; and $pass->private = $request->private ? 0 : 1; with the right values? I was prompted here that you can use Eloquent: Mutators.

The form:

<div class="form-group">
    <p>Пароль:</p>
    <input name="title" type="text" class="form-control"  required value="{{ $pass->title ?? ''}}">
</div>
<div class="form-group">
    <p>Для чего:</p>
    <input name="source" type="text" class="form-control"  required value="{{ $pass->source ?? ''}}">
</div>
<div class="form-group">
    <input type="checkbox" name="private">
        <label>Личный</label>
</div>
<div class="form-group">
    <label for="category_id">Категория</label>
    <select name="category_id" id="category_id" class="form-control">
        @foreach ($categorys as $category)
            <option value="{{$category->id}}">{{$category->title}}</option>
        @endforeach
    </select>
</div>


Controller:
public function store(Request $request) {
        $id = Auth::user()->id;
        $pass = new Pass();
        $pass->title = $request->title;
        $pass->source = $request->source;
        $pass->category_id = $request->category_id;
        $pass->user_id = $id;
        $pass->private = $request->private ? 0 : 1;
        $pass->save();
        return redirect()->route('home');
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey delphinpro, 2021-04-30
@deadloop

public function store(Request $request) {
  $validator = Validator::make($request->all(), [
    'title' => 'required|string',
    'source' => 'required|string',
    'category_id' => 'required|integer|exists:categories,id',
  ]);

  try {
    $input = $validator->validate();
  } catch (ValidationException $e) {
    return redirect()->back()->withErrors($validator)->withInput();
  }

  $input['id'] = Auth::user()->id;
  $input['private'] = $request->has('private') ? 0 : 1;

  Pass::create($input);

  return redirect()->route('home');
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question