Laravel password recovery template - laravel

I have the following code which sends a passowrds recovery mail:
public function recovery(Request $request)
{
$validator = Validator::make($request->only('email'), [
'email' => 'required'
]);
if($validator->fails()) {
throw new ValidationHttpException($validator->errors()->all());
}
$response = Password::sendResetLink($request->only('email'), function (Message $message) {
$message->subject(Config::get('boilerplate.recovery_email_subject'));
});
switch ($response) {
case Password::RESET_LINK_SENT:
return $this->response->noContent();
case Password::INVALID_USER:
return $this->response->errorNotFound();
}
}
Which I found out uses the following template: resources/views/auth/emails/password.php
which is an empty file.
How I can access the token from this template?
Isn't there any built-in view to use from laravel?

The function in your questions doesn't return a view.
Also, I'm unfamiliar with that path to the view that is in your question. Which version of Laravel are you using?
Anyhow, you can get the reset token from the DB, just like any other value in the DB. E.g. from a controller that is returning a view:
$user = User::find(Auth::id());
$remeber_token = $user->remember_token;
return view('to_your_view.blade.php', compact('remember_token');
And then in the view file:
{{ $remember_token }}
This will output it, no need to use echo or anything.
But, again, the function you pasted into your question is not a function that is returning a view, so I'm not sure where to tell you to put the above code.
As for your questoin about Laravel having an in-built view for 'this', in Laravel 5.3, at least, the view I assume you want will be within `resources/views/auth/passwords/'.

Related

Laravel validation couldn't store value after validate and give error 500

I have a form that using ajax for update data client. In that form there is an input file. Everything is going fine except for updating the file. File is sent, it changed on storage too, but it gives error on validation and didn't change data on database.
Here is the code on the controller :
public function update(Request $request, Client $client)
{
$validatedData = Validator::make($request->all(), [
'name' => 'required|max:255',
'logo'=> 'image|file|max:100',
'level' => 'required|max:1'
]);
$validatedData['user_id'] = auth()->user()->id;
if ($validatedData->fails()){
return response()->json($validatedData->errors());
} else {
if($request->file('logo')){
if($request->oldLogo){
Storage::delete($request->oldLogo);
}
$validatedData['logo'] = $request->file('logo')->store('logo-clients');
}
$validateFix = $validatedData->validate();
Client::where('id', $client->id)->update($validateFix);
return response()->json([
'success' => 'Success!'
]);
}
}
It gives error on line :
$validatedData['logo'] = $request->file('logo')->store('logo-clients');
With message :
"Cannot use object of type Illuminate\Validation\Validator as array"
I use the same code that works on another case, the difference is the other not using ajax or I didn't use Validator::make on file input. I guess it's just wrong syntax but I don't really know where and what it is.
To retrieve the validated input of a Validator, use the validated() function like so:
$validated = $validator->validated();
Docs:
https://laravel.com/docs/9.x/validation#manually-creating-validators
https://laravel.com/api/9.x/Illuminate/Contracts/Validation/Validator.html
$validatedData is an object of type Illuminate\Validation\Validator.
I would say the error is earlier there as well as this line should give an error also:
$validatedData['user_id'] = auth()->user()->id;
As ericmp said, you first need to retrieve the validateddata to an array and then work with it.

How to check data exists in the database

I have a function to add new property. But i want to check for duplicate data at column "code" before add new data into database. If data exists will appear a message error.
function addPro(Request $req)
{
$id = $req->type_id;
$type = AssetType::find($id);
if($req->save == 'save'){
$pro = new TypeProperties;
$pro->name = $req->name;
$pro->code = $req->code;
$pro->type = $req->type;
$pro->assettype_id = $req->type_id;
$pro->save();
Schema::table($type->code, function ($table) use ($pro) {
if ($pro->type == "textbox")
$table->string($pro->code )->nullable();
if ($pro->type == "textarea")
$table->text($pro->code )->nullable();
});
return redirect(url($type->id.'/add/property'))->with('message','Save successful');
}
return redirect(url('asset/type/'.$type->id));
}
You can use laravel Request Validation
function addPro(Request $req)
{
$id = $req->type_id;
$type = AssetType::find($id);
if($req->save == 'save'){
$req->validate([
'code' => 'required|unique:tablename'
]);
$pro = new TypeProperties;
$pro->name = $req->name;
$pro->code = $req->code;
$pro->type = $req->type;
$pro->assettype_id = $req->type_id;
$pro->save();
Schema::table($type->code, function ($table) use ($pro) {
if ($pro->type == "textbox")
$table->string($pro->code )->nullable();
if ($pro->type == "textarea")
$table->text($pro->code )->nullable();
});
return redirect(url($type->id.'/add/property'))->with('message','Save successful');
}
return redirect(url('asset/type/'.$type->id));
}
The most simple way to do this is by checking if code is_null :
if (is_null($pro->code)) {
// It does not exist
} else {
// It exists
}
The other way is to make a validation using Laravel's built in ValidateRequest class. The most simple use-case for this validation, is to call it directly in your store() method like this:
$this->validate($req, [
'code' => 'required|unique,
//... and so on
], $this->messages);
With this, you're validating users $req by saying that specified columns are required and that they need to be unique, in order for validation to pass. In your controller, you can also create messages function to display error messages, if the condition isn't met:
private $messages = [
'code.required' => 'Code is required',
'code.unique' => 'Code already exists',
//... and so on
];
You can also achieve this by creating a new custom validation class:
php artisan make:request StorePro
The generated class will be placed in the app/Http/Requests directory. Now, you can add a few validation rules to the rules method:
public function rules()
{
return [
'code' => 'required|unique,
//... and so on
];
}
All you need to do now is type-hint the request on your controller method. The incoming form request is validated before the controller method is called, meaning you do not need to clutter your controller with any validation logic:
public function store(StorePro $req)
{
// The incoming request is valid...
// Retrieve the validated input data...
$validated = $req->validated();
}
If you have any additional question about this, feel free to ask. Source: Laravel official documentation.
What does your migration look like for AssetType?
I ask because you can do this in the schema with ->unique() added to the column on the creation or make a migration to add the constraint.
You can also check with something like this:
// Search database table for entry
$entry = AssetType::where('code', '=', $pro->code)->first();
// If not found
if ($entry === null) {
// Save method here.
}
Otherwise, you can use the manual validator or create a Request with validation
References:
https://laravel.com/docs/5.8/queries#where-clauses
https://laravel.com/docs/5.8/validation#creating-form-requests
https://laravel.com/docs/5.8/validation#manually-creating-validators

Laravel if one of the fields is not set, laravel throws error

I have very big problem.
When I submit my form with data everything goes well, but when I won't fill one field in my form laravel throw error MethodNotAllowedHttpException in RouteCollection.php line 218
I have validation in my controller but it does not change anything. When the form is empty it throws an error.
Somebody has a solution for this error?
In your route for this form post use veriables as optional. Use ? In your route definition.
/{var?}/{var2?}/......
From laravel docs-
Occasionally you may need to specify a route parameter, but make the presence of that route parameter optional. You may do so by placing a ? mark after the parameter name. Make sure to give the route's corresponding variable a default value:
Route::get('user/{name?}', function ($name = null) {
return $name;
});
Route::get('user/{name?}', function ($name = 'John') {
return $name;
});
or
// validate the info, create rules for the inputs
$rules = array('data_rozpoczecia' => 'required', 'data_zakonczenia' => 'required');
// run the validation rules on the inputs from the form
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) { return redirect()->back(); } else{ //do what you want. }

Laravel 5 Authentication: Call to a member function getEmailForPasswordReset() on null

I'm using the authentication included with laravel 5.2
I have a problem at reset password form.
When I submit email, it returns this error:
Call to a member function getEmailForPasswordReset() on null
I found this cause by the following code:
$user->getEmailForPasswordReset()
the $user is null
In addition, I try to change Illuminate\Auth\Passwords\PasswordBroker at function emailResetLink
return $this->mailer->send($view, compact('token', 'user'), function ($m) use ($user, $token, $callback) {
$m->to($user->getEmailForPasswordReset());
if (! is_null($callback)) {
call_user_func($callback, $m, $user, $token);
}
});
I change: compact('token', 'user') -> ['token'=>$token, 'user2'=>$user]
And $user->getEmailForPasswordReset() -> $user2->getEmailForPasswordReset()
It works well!
Can you help me figure out what I did wrong?
Thanks.
The problem is definitely not in laravel files, so stop looking there and messing with the code, because you risk breaking more stuff than you will fix and also it will be overwritten once you do composer update.
The $user is null because the system cannot find the user you want to send a password reset link to. It would be more helpful to see your controller that implements the password resetting (submitting). Laravel comes with a pretty good starting point and you should not overengineer it unless needed: https://laravel.com/docs/5.2/authentication#resetting-routing
So the method for sending reset links would look something like this:
public function postEmail(Request $request)
{
$this->validate($request, ['email' => 'required|email']);
$response = Password::sendResetLink($request->only('email'), function (Message $message) {
$message->subject($this->getEmailSubject());
});
switch ($response) {
case Password::RESET_LINK_SENT:
return redirect()->back()->with('message', 'Password reset link sent');
case Password::INVALID_USER:
return redirect()->back()->with('message', 'User not found');
}
}
As you see there's no User objects involved for you to handle.

Pass value to URL - REST style

<h1>Edit page of {{ $user->username }}</h1>
{{ Form::open(['route' => 'user.store']) }}
... the rest of the view
This is in my login view. The related code in the store method in the controller looks like this:
if (Auth::attempt(Input::only('username', 'password'))) {
$user = Auth::user();
return Redirect::route('user.show', ['user' => $user]);
}
and the show method:
public function show($user)
{
return View::make('user.edit', ['user' => $user]);
}
And I get .../user/%7Buser%7D as URL (and I want it to be, eg. .../user/exampleusername) and also an exception: ErrorException: Trying to get property of non-object.
When I dd($user) in the show method (or in the view, doesn't matter), I get simply string[6] {user}, which means I do not pass the $user successfully to the user.show route.
The official docs give this example: return Redirect::route('profile', array('user' => 1)); which seems relevant to my case, which I think should look like this in my code: return Redirect::route('user.show', ['user' => $user]);?
Funny, though, if in the show method I try to take the user object from the session (Auth::user()), and dump it, as here:
public function show($user)
{
$user = Auth::user();
dd($user);
...
it will still be NULL, but if I dump it in the index method:
public function index()
{
if (Auth::check()) {
dd(Auth::user());
...
, then it returns correct object, full of parameters and values... I have no idea what's going on and why in one method I have the session object, but in the other I don't.
Any suggestions on how to go around this problem?
UPDATE: I narrowed it down to this implementation in the store method:
return Redirect::route('user.show')->with('user', $user);
and in the show method:
$user = Session::get('user');
return View::make('user.edit', ['user' => $user]);
Because apparently the only place where you can pass an array that will explode into single variables is in View::make, whereas in Redirect::to, Redirect::action and Redirect::route, etc., you must use the ->with('key', $value) function. Those values then will be available in the Session singleton.
Nevertheless, I still get .../%7Buser%7D in the URL. And I don't know how to get out of this...
You need to pass the id of the user to the user.show route - not the $user itself.
return Redirect::route('user.show', [$user->id]);

Resources