I'm new to Laravel, and I have been struggling to insert data into a certain table, hods
. The table only has two fields, a unique id, and a foreign key called user_id
.
Below is the code for the Hod
model:
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Hod extends Model
{
use HasFactory;
protected $table = 'hods';
protected $primaryKey = 'id';
protected $fillable = 'user_id';
}
Below is the code for the method in my controller where I want the query to take place:
public function createHOD(Request $request)
{
// Validate Form Input
$validator = Validator::make($request->all(), [
'name' => 'required|string|max:255',
'email' => 'required|email|unique:users,email,except,id',
'password' => 'required|string|min:8|confirmed',
]);
// If Validation Is Successful
if (!$validator->fails()) {
// Create User THIS QUERY WORKS FINE
$user = User::create([
'name' => $request->input('name'),
'email' => $request->input('email'),
'password' => Hash::make($request->input('password')),
'user_type' => "HOD"
]);
// Attaching 'HOD' Role To User
$user->attachRole('HOD');
// Adding The User To The HOD Table NOT WORKING
$hod = new Hod();
$hod->user_id = $user->id;
$hod->save();
// TRIED THIS TOO, ALSO NOT WORKING
DB::table('hods')->insert(
['user_id' => $user->id],
);
return response()->json(['success' => 'HOD Successfully Created.']);
} else {
// Return Error Messages
return response()->json(['error' => $validator->errors()->all()]);
}
}
I'm making use of AJAX
, below is the code that handles that aspect:
$("#hodSubmit").click(function(e) {
e.preventDefault();
var _token = $("input[name=_token]").val();
var name = $("input[name=hod_name]").val();
var email = $("input[name=hod_email]").val();
var password = $("input[name=hod_password]").val();
var password_confirmation = $("input[name=hod_confirmation]").val();
$.ajax({
url: "",
type: 'POST',
data: {
_token: _token,
name: name,
email: email,
password: password,
password_confirmation: password_confirmation
},
success: function(data) {
if ($.isEmptyObject(data.error)) {
$("#hodForm")[0].reset();
printSuccessMsg("hod");
} else {
printErrorMsg(data.error, "hod");
}
}
});
});
Please let me know if you require additional code or further explanation. Thanks
from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3cIwH1e
via IFTTT
Aucun commentaire:
Enregistrer un commentaire