Cant store number generated from str_random() into MySQL - laravel

i cant store the number generated from str_random() function. database stores all other inputs but not this, its always empty. it doesnt even show an error. it just stores it as empty text. i even checked with dd() function the $token variable contains a random string even after storing it to the database. its strange, i need help!!
public function store(Request $request)
{
$token="";
$chatToken1 = str_random(16);
$chatToken2 = str_random(16);
$token = $chatToken1.$chatToken2;
ChatMessage::create([
'to_user_id' => $request->get('to_user_id'),
'from_user_id' => auth()->user()->id,
'message' => $request->get('chat_message'),
'chat_key' => $token,
'status' => '1'
]);

Related

Laravel create command wont insert a value in database

Hello i am new to Laravel so currently im doing a CRUD. I have created this insert function that works well except one value is never inserted. This is the code below:
public function storeClient(Request $request) {
$request->validate([
'name' => 'required',
'email' => 'required|email',
'phone' => 'nullable',
'age'=>'required',
]);
Client::create($request->all());
dd($request->phone);
return redirect('/')->with('msg', 'Client Saved successfully!.');
}
the phone' => 'nullable', value will not insert in the database unless i update the existing values. I tried this command dd($request->phone); and it shows the correct value from the user input. Any idea why the value will be inserted as null on database?
This is the value output when i make the dd command
I tried this other code which works well but im trying to use the default create() function of laravel. This is the other code i did that works well:
public function storeClient()
{
$client = new Client();
$client->name = request('name');
$client->email = request('email');
$client->phone_number = request('phone');
$client->age = request('age');
$client->save();
return redirect('/')->with('msg','Client Saved successfully!');
}
first i did not like nullable here 'phone' => 'nullable',
then u should see what do you register in your Client table phone_number or phone,
$client->phone_number = request('phone');
i think you should rename your input name phone to phone_number and will work
When you are trying to use default create method the fields names must be same as in database.
$client->phone_number = request('phone');
this line works due to the name you entered manually.
to work with default create method change the name of field in database as phone.

Laravel 8 multiple models to single view Error $address Not defined

I'm trying to create 2 rows in the DB using findOrNew() but when I use the ID from the Users model to create another model(Address) the programs returns undefined variable $address. I don't know if I'm using the correct approach or not. Bellow you can view my approach. Can you lead me to the right approach or where to find it?
2 models one view:
seeing what you have in your method is returning an undefined because it is not executing the findOrNew method correctly, check this link, maybe it will help you and this same
the second is that if you are passing the values by post everything will come to you in the $req parameter and only there then if you want to use the id you would have to access through $req->id if you send the data correctly
the third I see that in the view method you are passing 3 parameters when you should only pass two the first the name of the view the second the arrangement with the data that you will pass to the view
public function detail(Request $req)
{
$user = User::firstOrNew($req->id);
$user->user_type_id = 1;
$user->name = $req->name;
$user->last_name = $req->last_name;
$user->email = $req->email;
$user->password = Hash::make(Str::random(8));
$user->save();
$address = UserAddress::firstOrCreate(['user_id' => $req->id]); //or maybe $user->id
return view('user.detail', [
'user' => $user,
'adderss' => $address
]);
}
finally you may prefer to use the updateOrCreate method
public function detailV2(Request $req)
{
$user = User::updateOrCreate(
['id' => $req->id],
[
'user_type_id' => 1,
'name' => $req->name,
'last_name' => $req->last_name,
'email' => $req->email,
'password' => Hash::make(Str::random(8)),
]
);
$address = UserAddress::firstOrCreate(['user_id' => $user->id]);
return view('user.detail', [
'user' => $user,
'adderss' => $address
]);
}

Validating form comaring two fields values

I'm trying to find Laravel 8 documentation on how to validate comparing two fields to each other. I'm creating an app that allows creating matches from teams in a database table, using the create() method in the controller. I looked into Laravel #Validation, even #Custom Validation Rules, but I can't find anything when comparing the two fields.
public function store(Request $request)
{
$validatedData = $request->validate([
'local_team' => 'required',
'local_score' => 'required|numeric',
'visitor_team' => 'required',
'visitor_score' => 'required|numeric',
]);
$score = new Score();
$score->local_team = $request->local_team;
$score->local_score = $request->local_score;
$score->visitor_team = $request->visitor_team;
$score->visitor_score = $request->visitor_score;
$score->save();
$new = true;
return redirect()->route('scores.show',
['id' => $score->id, 'new' => true]);
}
In my case, the 'local_team' and 'visitor_team' fields should be different. Any clue on how to do it?

Laravel send mail with multiple check box value

i'm trying to make inquiry form where costumer fill up form then check the value on the checkbox then once they submit form will send email to me listing all the information the customer selected, now problem is i want to change this[event_id,requirement_id] instead of id replace it with name those two id parameter is from my two model listed below.
Model:
Event:[id,name]
Requirement:[id,name]
Controller:
public function store(Request $request)
{
$summary=[
'name' => $request->fullname,
'email' => $request->email,
'company' => $request->company,
'event' => $request->event_id,
'requirement' => $request->requirement_id
];
return $summary;
Mail::send('emails.contact-message',[
],function($mail) use($summary){
$mail->from('myemail#gmail.com', 'tester');
$mail->to('myemail#gmail.com')->subject('Contact Message');
});
return redirect()->back();
}
This is the result of my return request:
{"name":"myname","email":"myemail#gmail.com","company":"mycompany","event":["1","2"],"requirement":["1","2"]}
As you can see the array Event has value of 1 and 2 i wanted to replace it with its name output should be [Wedding,Birthday] i'm sorry for my bad english hope you understand me..
Well, you'd need to pull the name from your models.
The following should do the trick:
$events = App\Event::whereIn('id', $request->event_id)
->get()
->pluck('name')
->toArray();
$requirements = App\Requirement::whereIn('id', $request->requirement_id)
->get()
->pluck('name')
->toArray();
Obviously, replace name in the above example with the actual name field in your models. This is just an example.
$events and $requirements will both be an array containing the names matching the ids you are supplying in your request.
You also need to change your $summary array as follows:
$summary = [
'name' => $request->fullname,
'email' => $request->email,
'company' => $request->company,
'event' => $events
'requirement' => $requirements
];

Can't authenticate user with Laravel Auth::Atempt

I'm struggling myself trying to find the reason but can't. It always falss to "else". I'm using sqliteand this is my code:
public function doLogin(Request $request)
{
$email = $request['email'];
$password = $request['password'];
if ( Auth::attempt(['email' => $email, 'password' => $password]) )
return redirect()->route('home');
return redirect()->back();
}
route
Route::post('/doLogin',['as' => 'doLogin', 'uses' => 'Auth\LoginController#doLogin']);
Already printed the variables, the values are exatcly the same as the database.
Possible cause of the problem ?
Testing the Variable Receiving Value (Prints the right values)
$usuario = \App\User::find(1)->pluck('email', 'password');
return ($usuario);
Printed Value:
{"teste123":"teste#teste.com"}
Also, If I try this:
public function doLogin(Request $request)
{
$email = $request->input('email');
$password = $request->input('password');
dd($request->all());
}
I get this:
array:4 [▼
"_token" => "xxxxxxxxxxxxxxxxxxxxxxxxxxx"
"email" => "teste#teste.com"
"password" => "teste123"
"action" => null
]
Is it normal action = null ?
It looks like you're storing your passwords in your database as plaintext, and that seems to be the issue. You should never do this, as if you have a security leak, then the infiltrator could easily have access to all of your users' passwords.
That also seems to be the issue as to why your Auth::attempt is failing. Auth::attempt goes into SessionGuard.php, which eventually calls validateCredentials from EloquentUserProvider.php. This function hashes the password it is given and checks that against what is in the database. Laravel is expecting your password in the database to be hashed (by default it is bcrypt), so the passwords are not matching. It hashes the plaintext password from the $request so it no longer matches the plaintext in your DB.
Laravel comes with the command php artisan make:auth. If you use this, then you shouldn't have to do your doLogin function. You can just send the logins along the default route. Then when you're testing, sign up your account through the registration to ensure that it's saved in your database in a hash, instead of plaintext.

Resources