Using a Mailable instead of a MailMessage for password reset emails in Laravel 5.5 - email

I'd like my application to use Mailables for all of the emails it sends, so I created my own ResetPasswordEmail class that extends Mailable. Then I created my own ResetPassword notification class that extends the vendor class of the same name and overrode the toMail method as follows:
public function toMail($notifiable)
{
return (new ResetPasswordEmail())->with('token', $this->token);
}
Then I overrode the sendPasswordResetNotification from the CanResetPassword trait in my User model like this:
public function sendPasswordResetNotification($token)
{
$this->notify(new ResetPassword($token));
}
Calling my custom ResetPassword notification class.
The problem is that if I use the default method of creating a MailMessage and sending it, it automatically populates the 'to' field with the user's email. But when I use my ResetPasswordEmail mailable class, it doesn't.
Is there a good way to get it to work like that with my custom mailable?

Well in the end I just set the "to" field for my Mailable instance like this:
public function toMail($notifiable)
{
return (new ResetPasswordEmail())->with('token', $this->token)->to($notifiable->email);
}
Since $notifiable is an instance of the User model in this case, I can get the email like that. I don't know if this is the best way to do it, but it works.

Related

Create Contactor with paramater for ExternalAction

How I can create Contactor in code effect for ExternalAction ,
I have this code
[ExternalAction(typeof(Service), "SendEmail")]
And I want send email when success Evaluate but without write send code in SendEmail, I want use call interface to send it , like this
private readonly IEmailService email;
public Service(IEmailService emailService)
{
email = emailService;
}
[Action("Send Email", "Send Email to Someone")]
public void SendEmail(Rule Rule, [Parameter(ValueInputType.User, Description = "Output message", DataSourceName = "UserList")] int userId)
{
email.sene(userId);
}
You are trying to use the instance action method. For the engine to be able to invoke such a method it needs to instantiate your type. Your Service class doesn't have an empty (parameterless/default) constructor. Obviously, the engine won't have an instance of your EmailService at evaluation time. Therefore, it can't invoke your instance method. Either add a default constructor to your Service class and find another way to pass EmailService to the Service class or use a static method with value type parameters.

Get SalesFormLetter class from SalesEditLines form formRun using PreHandler AX7

I need to make some changes on closeOk of SalesEditLines form. As I know, I am not able to change the standard methods, so I need to create an event handler for closeOk.
[PreHandlerFor(formStr(SalesEditLines), formMethodStr(SalesEditLines, closeOk))]
public static void SalesEditLines_Pre_closeOk(XppPrePostArgs args)
{
FormRun sender = args.getThis() as FormRun;
Object callerObject = sender.args().caller();
}
The question is - how can i access a SalesFormLetter through SalesEditLines form formRun using PreHandler?
You can see the following line in init method of SalesEditLines form
salesFormLetter = element.args().caller();
So your callerObject is an instance of SalesFormLetter class, you need just cast it to proper type.
Please check the following link:
https://learn.microsoft.com/en-us/dynamicsax-2012/developer/expression-operators-is-and-as-for-inheritance

Getting method name related to a rest service

I wanted to know if there exist a way of retrieving the actual method name associated to a rest service provided. Lets suppose my url is http://localhost:8080/v1/mytesturl now i want to retrieve the actual method name that is associated with this url.
Actually we are maintaining some key/value pair specific to the method that we have created and i need to make some checks based on the method name that gets executed using these values.
Plz let me know if there exist some way to do that..
Simply get the method name from the Object class.
#RestController
#RequestMapping("")
public class HomeController {
#RequestMapping("/mytesturl")
#ResponseBody
public String getMethodName() {
return new Object(){}.getClass().getEnclosingMethod().getName();
}
}
i got the solution by using this
Map<RequestMappingInfo, HandlerMethod> handlerMethods = RequestMappingHandlerMapping.getHandlerMethods();
HandlerExecutionChain handler = RequestMappingHandlerMapping.getHandler(requestr);
HandlerMethod handler1 = null;
if(Objects.nonNull(handler)){
handler1 = (HandlerMethod) handler.getHandler();
handler1.getMethod().getName()
}
this provide me with what i wanted..

Is splitting an index action into multiple ones a restful-friendly approach?

I need to display two different index pages to two different user groups. For example, a regular user should see one page, and a privileged user - another one. I see two ways of approaching this issue:
One index action with conditionals:
public function index()
{
// view for privileged users
if(request()->user()->hasRole('privileged')){
return view('index_privileged');
}
// view for regular users
if(request()->user()->hasRole('regular')){
return view('index_regular');
}
return redirect('/');
}
Multiple actions:
public function index_privileged()
{
return view('index_privileged');
}
public function index_regular()
{
return view('index_regular');
}
Which approach is more "restful-friendly" and generally better?
I'm a big fan of light controllers. This might be a little overboard for a simple problem but if something like this pops up again, you'd already have everything all setup.
With that said, it might be best to create a PrivilegedUser class and a RegularUser class and give them both an index method which returns their respective views. Code them both to an interface UserInterface and make sure they both implement that.
Here is what those looked like in my test.
class RegularUser implements UserInterface
{
public function index()
{
return view('index_regular');
}
}
class PrivilegedUser implements UserInterface
{
public function index()
{
return view('index_privileged');
}
}
interface UserInterface
{
public function index();
}
Then you can add a listener which should run for the event Illuminate\Auth\Events\Login. Laravel will fire this event for you automatically when someone logs in. This goes into the file EventServiceProvider.php.
protected $listen = [
'Illuminate\Auth\Events\Login' => [
'App\Listeners\AuthLoginListener',
],
];
Now you can run php artisan event:generate to generate the new listener. Here is what my listener looks like, it should work for you.
namespace App\Listeners;
use Illuminate\Auth\Events\Login;
use Illuminate\Foundation\Application;
class AuthLoginListener
{
/**
* Create the event listener.
*
* #param Application $app
*/
public function __construct(Application $app)
{
$this->app = $app;
}
/**
* Handle the event.
*
* #param Login $event
* #return void
*/
public function handle(Login $event)
{
if ($event->user->hasRole('privileged')) {
$this->app->bind('App\Repositories\UserInterface', 'App\Repositories\PrivilegedUser');
} else if ($event->user->hasRole('regular')) {
$this->app->bind('App\Repositories\UserInterface', 'App\Repositories\RegularUser');
}
}
}
Essentially what this is doing is telling Laravel to load up a certain class based on the type of user that just logged in. The User instance is available through the Login object which was automatically passed in by Laravel.
Now that everything is setup, we barely have to do anything in our controller and if you need to do more things that are different depending on the user, just add them to the RegularUser or PrivilegedUser class. If you get more types of users, simply write a new class for them that implements the interface, add an additional else if to your AuthLoginListener and you should be good to go.
To use this, in your controller, you'd do something like the following...
// Have Laravel make our user class
$userRepository = App::make('App\Repositories\UserInterface');
return $userRepository->index()->with('someData', $data);
Or even better, inject it as a dependency.
use App\Repositories\UserInterface;
class YourController extends Controller
{
public function index(UserInterface $user)
{
return $user->index();
}
}
Edit:
I just realized I forgot the part where you wanted to return redirect('/'); if no condition was met. You could create a new class GuestUser (I know this sounds like an oxymoron) which implements UserInterface but instead of using the AuthLoginListener, I'd bind it in a service provider when Laravel boots. This way Laravel will always have something to return when it needs an implementation of UserInterface in the event it needs this class if no one is logged in.
Well, its more like a refactoring "issue" than a rest-friendly issue. Check this guideline and you can see that most of the things that makes an api friendly is concerned to the url.
But, lets answer what you are asking. The thing you wanna do is a refactoring method but it is not only the move method but something like the extract variable.
The second option would make the code more readable, either ways are right but the second is more developer friendly. It enhances the code readability from any developer. I would recommend using the second option.
Refactoring is never enough, but read something like this, it will help you a lot writing more readable codes.

Can't extend my class to Eloquent while it's already extended to BaseController

I have a ListingsController that extends BaseController which is fine, my app works.
But now I intend to create a new ContactController and create a relation between it and ListingController.
Each listing should have 1 contact and there's a contact_id field in listings table.
The problem is, to use that, I need to extend my class to Eloquent and it's already extended to BaseController and if I change that my app crashes down.
Is there a solution for this?
Thanks.
As SUB0DH said, relationships should be declared in the Model, not in the Controller, you'd want to have something like this in your Listing model:
public function contact()
{
return $this->hasOne('Contact');
}
and in your Contact model you can link the contact to a listing by using
public function user()
{
return $this->belongsTo('User');
}
Be sure to read http://laravel.com/docs/eloquent#one-to-one