K
K
Karpkarp2019-12-04 23:09:17
Laravel
Karpkarp, 2019-12-04 23:09:17

How to use insert in laravel?

There is a simple form

<div class="form-group">
    <label for="examplelogin1">Login</label>
    <input type="login" class="form-control" id="login" placeholder="login">
  </div>

  <div class="form-group">
    <label for="exampleInputEmail1">Email</label>
    <input type="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter email">
  </div>

  <div class="form-group">
    <label for="exampleInputPassword1">Password</label>
    <input type="password" class="form-control" id="password" placeholder="Password">
  </div>

  <button type="submit" class="btn btn-primary">Submit</button>

</form>

And the code that inserts records into the database:
class TestController extends Controller
{
    public function index() 
    {
    	$id = DB::table('users')->insert(array(
        array('login' => 'karp', 'email' => '[email protected]','password' => 'q1w2e3r4' )
    ));
    }
}

How to link the form with this code? What would be the data that was typed into the form, flew to the database.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Y
Yuri Kulaxyz, 2019-12-04
@Kulaxyz

I would suggest using eloquent then the code would look like this

public function index(Request $request) 
{
  $data = $request->except('_token');
  User::create($data);
}

Or you can get the data separately: In general, read the documentation, instead of asking the basics on the toaster

N
Nikolai Smirnov, 2019-12-05
@Bzdykin

In the form, you specify in the action attribute the route where you will send the form data, and in the method attribute you specify post. In the /routes/web.php file, you specify that the post request for the route that you specified in the form will be processed by the index method of the TestController controller.
Next, in the method, be sure to validate the data received from the form. To do this, it is better to use form request validation so as not to clutter up the controller with validation logic, but put it in a separate file.
Use Eloquent to add records to a database table, and use QueryBuilder only in complex queries where Eloquent's capabilities are lacking.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question