I am working on an app with Laravel 8.
I use the following method to add new users to the users
table:
public function insert() {
//Check if user already exists
$user = User::where('email', '=', session('userEmail'))->first();
if (!$user) {
return User::create([
'first_name' => session('firstName'),
'last_name' => session('lastName'),
'email' => session('userEmail'),
'role_id' => 1
]);
}
else {
return redirect('/users')->with('error', 'User aleady exists!);
}
}
The problem:
I wanted to add a success confirmation message of "User created successfully". For this purpose, I did:
if (!$user) {
return User::create([
'first_name' => session('firstName'),
'last_name' => session('lastName'),
'email' => session('userEmail'),
'role_id' => 1
])->with('success', 'User created successfully');
}
For a reason I have not been able to find out, this fails. With this message:
Argument 1 passed to Symfony\Component\HttpFoundation\Response::setContent() must be of the type string or null, object given, called in
What am I doing wrong?
CodePudding user response:
The problem is that you are returning a User object and not a response.
Try this:
if (!$user) {
User::create([
'first_name' => session('firstName'),
'last_name' => session('lastName'),
'email' => session('userEmail'),
'role_id' => 1
]);
return redirect('/users')->with('success', 'User created successfully');
}