Как через fetch-запрос передать данные к контроллеру и поместить их в базу данных ( Laravel )
Хочу передать данные формы регистрации через fetch-запрос к контроллеру , чтобы при регистрации не было перезагрузки страницы и переадресации. Сработает ли , если я буду использовать json_encode(file_get_contents(php://input)) в файле User ? Или стоит отправлять данные через Routes к контроллеру ? ( Но мне при этом нужно, чтобы страница не перезагружалась. )
fetch-запрос
btnSignup.onclick = () => {
let input_name = document.querySelector("#input_name").value;
let input_surname = document.querySelector("#input_surname").value;
let input_login = document.querySelector("#input_login").value;
let input_email = document.querySelector("#input_email").value;
let input_password = document.querySelector("#input_password").value;
let response = await fetch("?", {
method: 'POST',
headers:{"Content-Type":'application/json'},
body:JSON.stringify({
"name":input_name ,
"surname":input_surname,
"login":input_login,
"email":input_email,
"password":input_password
})
});
let data = await response.json();
console.log(data);
};
Модель User
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'surname', 'login', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Register Controller
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\Models\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller
{
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* @var string
*/
// protected $redirectTo = RouteServiceProvider::HOME;========================
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* @param array $data
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* @param array $data
* @return \App\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'surname' => $data['surname'],
'login' => $data['login'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}