Laravel Trying to get property of non-object when sending emails - php

I'm making a function that each time I add a comment to a Support ticket it sends an email to the user but I'm getting getting Trying to get property of non-object when I submit the comment this only happens if I'm logged out of the users account and only logged into the Admin user
AdminComment Controller Code
<?php
namespace App\Http\Controllers;
use App\Comment;
use App\Mailers\AppMailer;
use App\Ticket;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AdminCommentController extends Controller
{
public function postComment(Request $request, AppMailer $mailer)
{
$this->validate($request, [
'comment' => 'required',
]);
$comment = Comment::create([
'ticket_id' => $request->input('ticket_id'),
'user_id' => Auth::user()->id,
'comment' => $request->input('comment'),
]);
$mailer->sendTicketComments($comment->ticket->user, Auth::user(), $comment->ticket, $comment);
return redirect()->back()->with('warning', 'There was a problem sending your comment to the customer via email');
}
}
here is the Mailer Controller
<?php
namespace App\Mailers;
use App\Status;
use App\Ticket;
use Illuminate\Contracts\Mail\Mailer;
class AppMailer
{
protected $mailer;
/**
* email to send to.
*
* #var [type]
*/
protected $to;
/**
* Subject of the email.
*
* #var [type]
*/
protected $subject;
/**
* view template for email.
*
* #var [type]
*/
protected $view;
/**
* data to be sent along with the email.
*
* #var array
*/
protected $data = [];
public function __construct(Mailer $mailer)
{
$this->mailer = $mailer;
}
/**
* Send Ticket information to the user.
*
* #param User $user
* #param Ticket $ticket
*
* #return method deliver()
*/
public function sendTicketInformation($user, Ticket $ticket)
{
$statuses = Status::all();
$this->to = $user->email;
$this->subject = "TechWiseDirect Support Ticket - [Reference #: $ticket->ticket_id]";
$this->view = 'users.emails.ticket_info';
$this->data = compact('user', 'ticket', 'statuses');
return $this->deliver();
}
/**
* Send Ticket Comments/Replies to Ticket Owner.
*
* #param User $ticketOwner
* #param User $user
* #param Ticket $ticket
* #param Comment $comment
*
* #return method deliver()
*/
public function sendTicketComments($ticketOwner, $user, Ticket $ticket, $comment)
{
$this->to = $ticketOwner->email;
$this->subject = "RE:[Ticket ID: $ticket->ticket_id]";
$this->view = 'users.emails.ticket_comments';
$this->data = compact('ticketOwner', 'user', 'ticket', 'comment');
return $this->deliver();
}
/**
* Do the actual sending of the mail.
*/
public function deliver()
{
$this->mailer->send($this->view, $this->data, function ($message) {
$message->from('test#test')
->to($this->to)->subject($this->subject);
});
}
}

the error happens for the Auth::user()->id I think. it's because you are logged out of your account. my guess is that you haven't used guard and only have one main user model defined for laravel.

Related

Laravel mail provide sender detail

I need to get my user email address along with form data in order to set ->from() in my mailable file
code
controller function
public function store(Request $request)
{
$request->validate([
'product' => 'required|string',
'email' => 'required|email',
'message' => 'required|string',
]);
$user = $request->user(); // need to add this
$inquery = new Inquery;
$inquery->user_id = $user->id;
$inquery->product = $request->input('product');
$inquery->email = $request->input('email');
$inquery->message = $request->input('message');
$inquery->save();
Mail::to('xyz#example.com')->send(new InquiryToAdmin($inquery));
}
Mailable file
class InquiryToAdmin extends Mailable
{
use Queueable, SerializesModels;
public $data;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($data)
{
$this->data = $data;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->from($user['email'])->subject('New Inquiry was sent')->view('emails.inquiry.admin');
}
}
NOTE:
What I need is to get ->from($user['email']) for that i need to send my $user from controller to mailable file (commented in code), the problem is I cannot set $user to be send to my mailable file.
Any idea?
try this
Mail::to('xyz#example.com')->send(new InquiryToAdmin($inquery,$user));
class InquiryToAdmin extends Mailable
{
use Queueable, SerializesModels;
public $data;
protected $user;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($data,$user)
{
$this->data = $data;
$this->user = $user;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->from($this->user->email)->subject('New Inquiry was sent')->view('emails.inquiry.admin');
}
}

Notifications wont work Laravel

i've implemented notifications on my app.And they were working fine until yesterday out of the blue the stopped working.now when i click on the route that enables the notification it just keeps loading this is the store method on my controller where i check if the email notifications are enabled and if they are the user should recieve an email everytime a project is published
public function store(Request $request){
$this->validate(request(), [
'title' => 'required|max:255|unique:projects',
'body' => 'required|max:1000',
// 'tutorial' => 'required|max:1000',
'avatar' => 'required|mimes:jpeg,bmp,png',
'zip_file' => 'required|mimes:zip,rar',
]);
$user = User::all();
$profiles_storage = storage_path('app/avatars/');
$project = new Project;
$project -> user_id = auth()->id();
$project -> title = request('title');
$project -> body = request('body');
$project -> tutorial = request('tutorial');
$project -> views = '0';
$project -> downloads = '0';
$project -> alternative_text = config('app.name').' '.request('title').' '.'project';
$profile = request()->file('avatar');
// $profile->store('profiles');
$project->image = $profile->hashName();
$image = Image::make($profile->getRealPath());
$image->fit(640, 360, function ($constraint)
{ $constraint->upsize();})->save($profiles_storage.$profile->hashName());
request()-> file('zip_file')->store('zip_files');
$project -> zip_file = request()->file('zip_file')->hashName();
$project -> save();
$category = $request->input('categories');
$project->categories()->sync($category);
foreach ($user as $u) {
if ($u->email_notifications != 0) {
$u->notify(new ProjectPublished($project));
}
}
session()->flash('message',"{$project->title}".' created');
return redirect('/admin/projects');
}
and this is the ProjectPublished.php
<?php
namespace App\Notifications;
use App\User; use App\Project; use Illuminate\Bus\Queueable; use Illuminate\Notifications\Notification; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Messages\MailMessage;
class ProjectPublished extends Notification { use Queueable; protected $project;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct(Project $project)
{
$this->project = $project;
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return ['mail'];
}
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->greeting('Hello there')
->subject('New Project:'.$this->project->title)
->line('As requested we are letting you know that a new project was published at Rek Studio')
->action('Check it out', url('projects/'.$this->project->title));
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toArray($notifiable)
{
return [
//
];
}
}
can anyone help me out?

Notifications for comments are working but for likes not working in laravel

I am trying to send notifications to the owner of the post when some like and comment on his post, notifications for comments are working but when I do the same work for likes it is not working.
here is my notification class
<?php
namespace App\Notifications;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
class show_notification extends Notification
{
use Queueable;
protected $comment;
protected $likes;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct($comment,$likes)
{
$this->comment = $comment;
$this->likes = $likes;
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return ['database'];
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toDatabase($notifiable)
{
return [
'comment' => $this->comment,
'likes' => $this->likes,
'user' => auth()->user()
//'repliedTime' => Carbon::now()
];
}
public function toArray($notifiable)
{
return [
//
];
}
}
My controller function code for notifications on comments
$id = $comment->post_id;
$getuser = Post::where('id', $id)->first();
$userid = $getuser->user_id;
if ($userid != $user_id ){
$user = User::where('id', $userid)->first();
$user->notify(new show_notification($comment));
}
My controller function code for notifications on likes
$id = $likes->post_id;
$getuser = Post::where('id', $id)->first();
$userid = $getuser->user_id;
if ($userid != $user_id ){
$user = User::where('id', $userid)->first();
$user->notify(new show_notification($likes));
}

Password Reset Not working in Laravel 5.4

I am new to laravel. I want to implement the login and registeration using laravel auth. I have implemented the login and registration flow successfully but I am not able to implement reset password.
I am facing the following issue:
1. After submitting the username/email some processing happens but I am not able to send the password reset link using the email. It always got a screen which says we have emailed your password reset link but nothing is happening. The entries are being made in the password_resets table.
Any help will be much appreciated.
I am using the gmail to send the password reset emails. After doing a lot of debugging everything looks fine apart from ResetPassword.php file which is executed till
public function via($notifiable)
{
// echo "<pre>".print_r($notifiable,1)."</pre>";exit("<br/>sdds");
return ['mail'];
}
There is a function in this file which is created to send the emails but this function is not going called. The function is given below :
/**
* Build the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
echo "<pre>".print_r($notifiable,1)."</pre>";exit();
return (new MailMessage)
->line('You are receiving this email because we received a password reset request for your account.')
->action('Reset Password', route('password.reset', $this->token))
->line('If you did not request a password reset, no further action is required.');
}
Here are the main file used in this
Authorisation model class RetailUserAuth.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\ResetsPasswords;
use Illuminate\Auth\Passwords\CanResetPassword;
class RetailUserAuth extends Authenticatable
{
use Notifiable;
//protected $primaryKey = 'user_id';
protected $table = 'retail_user_auth';
public $timestamps = false;
protected $fillable = ['username', 'user_id', 'password','source','user_status'];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
SendsPasswordResetEmails.php
<?php
namespace Illuminate\Foundation\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Password;
trait SendsPasswordResetEmails
{
/**
* Display the form to request a password reset link.
*
* #return \Illuminate\Http\Response
*/
public function showLinkRequestForm()
{
return view('auth.passwords.email');
}
/**
* Send a reset link to the given user.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse
*/
public function sendResetLinkEmail(Request $request)
{
$this->validate($request, ['username' => 'required|email']);
// We will send the password reset link to this user. Once we have attempted
// to send the link, we will examine the response then see the message we
// need to show to the user. Finally, we'll send out a proper response.
$response = $this->broker()->sendResetLink(
$request->only('username')
);
//echo "</pre>".print_r($response,1)."</pre>";exit();
return $response == Password::RESET_LINK_SENT
? $this->sendResetLinkResponse($response)
: $this->sendResetLinkFailedResponse($request, $response);
}
/**
* Get the response for a successful password reset link.
*
* #param string $response
* #return \Illuminate\Http\RedirectResponse
*/
protected function sendResetLinkResponse($response)
{
return back()->with('status', trans($response));
}
/**
* Get the response for a failed password reset link.
*
* #param \Illuminate\Http\Request
* #param string $response
* #return \Illuminate\Http\RedirectResponse
*/
protected function sendResetLinkFailedResponse(Request $request, $response)
{
return back()->withErrors(
['username' => trans($response)]
);
}
/**
* Get the broker to be used during password reset.
*
* #return \Illuminate\Contracts\Auth\PasswordBroker
*/
public function broker()
{
return Password::broker();
}
}
CanResetPassword.php
<?php
namespace Illuminate\Auth\Passwords;
use Illuminate\Auth\Notifications\ResetPassword as
ResetPasswordNotification;
trait CanResetPassword
{
/**
* Get the e-mail address where password reset links are sent.
*
* #return string
*/
public function getEmailForPasswordReset()
{
return $this->username;
}
/**
* Send the password reset notification.
*
* #param string $token
* #return void
*/
public function sendPasswordResetNotification($token)
{
$this->notify(new ResetPasswordNotification($token));
}
}
ResetPassword.php
<?php
namespace Illuminate\Auth\Notifications;
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Messages\MailMessage;
class ResetPassword extends Notification
{
/**
* The password reset token.
*
* #var string
*/
public $token;
/**
* Create a notification instance.
*
* #param string $token
* #return void
*/
public function __construct($token)
{
//echo $token;exit('<br/>fdfdffd');
$this->token = $token;
}
/**
* Get the notification's channels.
*
* #param mixed $notifiable
* #return array|string
*/
public function via($notifiable)
{
// echo "<pre>".print_r($notifiable,1)."</pre>";exit("<br/>sdds");
return ['mail'];
}
/**
* Build the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
echo "<pre>".print_r($notifiable,1)."</pre>";exit();
return (new MailMessage)
->line('You are receiving this email because we received a password reset request for your account.')
->action('Reset Password', route('password.reset', $this->token))
->line('If you did not request a password reset, no further action is required.');
}
}

Unable to Verify user in laravel

I'm new to laravel, so i started by creating a messaging application. User should be able to send message to each other. So i created migrations, seeds,models and also defined relationships in models. Everything was working fine. I was able to seed perfectly.
So i created a login page, applied validations. But now i'm unable to login.
Here is the route :
Route::group(array('prefix'=>'social'), function(){
Route::get('/', array('as' => 'loginformshow', 'uses' => 'LoginformController#showLogin'));
Route::post('loginform', array('as'=>'loginformdo', 'uses'=>'LoginformController#doLogin'));
Route::get('loggedin', array('as'=>'loggedin', 'uses'=>'LoginformController#loggedin'));
});
Here's the respective method in controller
public function doLogin(){
$rules = array('email'=> 'required|email', 'password'=>'required');
$validator = Validator::make(Input::all(), $rules);
if($validator->fails()){
return Redirect::to('social')->withErrors($validator)->withInput(Input::except('password'));
}else {
$userdata = array('email' => Input::get('email'), 'password' => Input::get('password'));
if(Auth::attempt($userdata)) {
return Redirect::route('loggedin');
}else echo "Invalid User";
}
}
Auth::attempt is returning false every time and so the output is Invalid User.
i used print_r to check the data received in $userdata and it's showing correct credentials.
Here's the User model:
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password');
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* #return string
*/
public function getReminderEmail()
{
return $this->email;
}
public function conversationsReply(){
return $this->hasMany('ConversationReply', 'user_id', 'id');
}
}

Categories