Sending email passing name in laravel - laravel-5

I'm trying to send an email to a user by entering his name and I look for the user's email with this name, but it does not work, the success message appears but in my email I receive nothing. what am I doing wrong?
if(User::where('name', '=', $destinatario)->exists()){
$exists = DB::table('users')
->select('email')
->where('name', $destinatario)
->get();
Mail::to($exists)->send(new TestEmail($remetente, $nome, $assunto, $exists, $mensagem));
return back()->with('sucess', 'Message sent!');
}else{
return back()->with('error', 'User does not exist!');
}
Mailable:
public function __construct($remetente, $nome, $assunto, $destinatario, $data)
{
$this->remetente = $remetente;
$this->nome = $nome;
$this->assunto = $assunto;
$this->destinatario = $destinatario;
$this->data = $data;
}
public function build()
{
//$address = 'gabriel.jg04#gmail.com';
$subject = 'E-mail de Usuário';
$name = 'Juelito';
return $this->view('emails.test',['texto'=>$this->data])
->from($this->remetente, $this->nome)
->replyTo($this->destinatario, $name)
->subject($this->assunto);
}

Problem is with get(). get() returns collection of users.
But your mailable expect single user.
If you want to send mail to one person you could do like that:
$user = User::where('name', '=', $destinatario)->first();
if($user){
Mail::to($user)->send(new TestEmail($remetente, $nome, $assunto, $user, $mensagem));
return back()->with('sucess', 'Message sent!');
} else {
return back()->with('error', 'User does not exist!');
}
If you want to send mail to multiple persons you could do like that:
$users = User::where('name', '=', $destinatario)->get();
if($users->count()){
foreach($users as $user){
Mail::to($user)->send(new TestEmail($remetente, $nome, $assunto, $user, $mensagem));
}
return back()->with('sucess', 'Message sent!');
} else {
return back()->with('error', 'User does not exist!');
}
Mailable:
public function __construct($remetente, $nome, $assunto, $destinatario, $data)
{
$this->remetente = $remetente;
$this->nome = $nome;
$this->assunto = $assunto;
$this->destinatario = $destinatario;
$this->data = $data;
}
public function build()
{
return $this->view('emails.test', ['texto' => $this->data])
->from($this->remetente, $this->nome)
->replyTo($this->destinatario->email, $this->desctinario->name)
->subject($this->assunto);
}

Related

I am unable to login with email or contact number using laravel

I am trying to login with email or contact no but unfortunately i am unable to login with contact number please help me how can i resolve that ? thanks.
Note :- I want to login with email or contact number.
login Controller
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(Request $request)
{
if ($request->username) {
$user = User::where('email', $request->username)->first();
} else if ($request->username) {
$user = User::where('contact_no', $request->username)-
>first();
}
if ($user ? Hash::check($request->password, $user->password) : null) {
$temp_login_code = Hash::make(Str::random(100));
$user->temp_login_code = $temp_login_code;
$user->update();
$url = config('property.cms_login_url') . '?code=' . $temp_login_code;
return redirect($url);
}
return redirect()->back();
}
Just change your query condition to this:
if ($request->username) {
$user = User::where('email', $request->username)
->orWhere('contact_no', $request->username)
->first();
}
done, Though no idea why you are making temp login codes.
public function index(Request $request)
{
$key = (strpos($request->username, '#') !== false) ? 'email' : 'contact_no';
if (Auth::attempt([$key => $request->username, 'password' => $request->password])) {
$user = Auth::user();
$temp_login_code = Hash::make(Str::random(100));
$user->update([
'temp_login_code' => $temp_login_code,
]);
$url = config('property.cms_login_url') . '?code=' . $temp_login_code;
return redirect($url);
}
return redirect()->back();
}

Not updating database and not throwing error in laravel

I have an issue while updating the user. When I try to update the user after clicking the save button then it redirect me to the same page and not throwing me any error but also its not updating anything in the database. Below is my code. I have no idea what's going on here. Help me :)
Controller
public function update(ReportRequest $request, $id)
{
$report = Report::findOrFail($id);
$input = $request->all();
if ($file = $request->file('photo_id')) {
$name = time() . $file->getClientOriginalName();
$file->move('images', $name);
$photo = Photo::create(['file' => $name]);
$input['photo_id'] = $photo->id;
}
$report->update($input);
return redirect()->back();
}
Route
Route::resource('admin/reports', 'ReportController', ['names'=>[
'index'=>'admin.reports.index',
'create'=>'admin.reports.create',
'edit'=>'admin.reports.edit',
]]);
Models
class Report extends Model
{
protected $fillable = [
'student_id',
'student_name',
'class_id',
'subject',
'teacher_name',
'report_categories_id',
'total_marks',
'obtained_marks',
'percentage',
'position',
'photo_id',
];
public function photo() {
return $this->belongsTo('App\Photo');
}
public function studentsClass() {
return $this->belongsTo('App\StudentsClass', 'class_id');
}
public function student() {
return $this->belongsToMany('App\Student');
}
}
Make sure you have your $fillable properties in your Photo and Report models, otherwise the create() and update() methods won't work as expected.
Check the $fillable fields in the Model as above. If the error persists check your laravel log on storage/logs/laravel.log.
In controller:
public function update(ReportRequest $request, $id){
$report = Report::findOrFail($id);
$input = $request->all();
try{
if ($request->photo_id != '') {
$path = 'images/';
$file = $request->photo_id;
$name = time() . $file->getClientOriginalName();
$file->move($path, $name);
$photo = Photo::create(['file' => $name]);
$report->update(['photo_id' => $photo->id]);
}
return redirect()->back();
}catch(\Exception $e){
return redirect()->back()->with('error_message', $e->getMessage());
}
}

Laravel Filter with multiple values

When trying to filter with only username or email code works fine.But when i am trying to filter with both email and username it returns empty.what i am missing
User model
public function scopeEmail($query, $email)
{
$query->where('email','=', $email);
}
public function scopeUsername($query, $username)
{
$query->where('username','=', $username);
}
Controller:
public function filter(Request $request)
{
$q = User::query();
$email = $request->input('email');
$username= $request->input('username');
if (isset($email))
{
// simple where here or another scope, whatever you like
$q->Email($request->input('email'));
}
if (isset($username))
{
$q->Username($request->input('username'));
}
//execute
$results = $q->get();
return response()->json(['issError'=>0, 'errorCode'=>0,'message'=>$results],200);
}
Use When to make filter easy:
public function filter(Request $request)
{
$q = User::query();
$email = $request->input('email');
$username= $request->input('username');
$q->when($email,function ($query){
$query->where('email',$email);
});
$q->when($username,function ($query){
$query->where('username',$username);
});
$results = $q->get();
return response()->json(['issError'=>0, 'errorCode'=>0,'message'=>$results],200);
}
Use simple where in if statements
public function filter(Request $request)
{
$q = User::query();
$email = $request->input('email');
$username= $request->input('username');
if (isset($email))
{
// simple where here or another scope, whatever you like
$q = $q->where('email', $request->input('email'));
}
if (isset($username))
{
$q = $q->where('username', $request->input('username'));
}
//execute
$results = $q->get();
return response()->json(['issError'=>0, 'errorCode'=>0,'message'=>$results],200);
}
Try this
public function filter(Request $request)
{
$q = User::query();
$email = $request->input('email');
$username= $request->input('username');
if (!is_null($email))
{
$q = $q->where('email', $email);
}
if (!is_null($username))
{
$q = $q->where('username', $username));
}
$results = $q->get();
return response()->json(['issError'=>0, 'errorCode'=>0,'message'=>$results],200);
}

laravel session route redirection error on multiple input fields

I have the following controller whenever i hit submit it redirects me to sales. Where as it should return admin.invoice.index page rather than sale.index. can any one please help?
$data = array();
for ($i=0; $i < count($request['product_id']); ++$i)
{
$sales= new Sale;
$sales->product_id = $request['product_id'][$i];
$sales->qty= $request['qty'][$i];
$sales->user_id = Auth::user()->id;
$sales->save();
$product = new Product;
$product->where('id', '=', $request['product_id'][$i])->decrement('stock', $request['qty'][$i]);
$data[]['sales'] = $sales;
$data[]['product'] = $product;
}
$data = [];
if ($request->session()->has('data')) {
$data = $request->session()->get('data');
}
Session::flash('success', 'Sale is successfully');
return view('admin.invoice.index')->with('data', $data);
}
Pass the data with with() through session.
{
$data = array();
for ($i=0; $i < count($request['product_id']); ++$i)
{
$sales= new Sale;
$sales->product_id = $request['product_id'][$i];
$sales->qty= $request['qty'][$i];
$sales->user_id = Auth::user()->id;
$sales->save();
$p = new Product;
$p->where('id', '=', $request['product_id'][$i])->decrement('stock', $request['qty'][$i]);
$product = Product::where('id', '=', $request['product_id'][$i])->first();
$data[$i]['sales'] = $sales;
$data[$i]['product'] = $product;
}
Session::flash('success', 'Sale is successfully');
return redirect('/invoice')->with('data', $data);
}
Then, Make a new route -
Route::get('/invoice', function(\Illuminate\Http\Request $request){
$data = [];
if ($request->session()->has('data')) {
$data = $request->session()->get('data');
}
return view('admin.invoice.index')->with('data', $data);
});
#Sohel0415
My Sales Controller is like this.
public function index()
{
$sales = Sale::orderBy('id', 'DESC')->get();
return view('admin.sales.index', compact('sales'));
}
public function create()
{
$products = Product::pluck('name', 'id', 'qty')->toArray();
return view('admin.sales.create', compact('products'));
}
public function store(Request $request)
{
$data = array();
for ($i=0; $i < count($request['product_id']); ++$i)
{
$sales= new Sale;
$sales->product_id = $request['product_id'][$i];
$sales->qty= $request['qty'][$i];
$sales->user_id = Auth::user()->id;
$sales->save();
$product = new Product;
$product->where('id', '=', $request['product_id'][$i])->decrement('stock', $request['qty'][$i]);
$data[]['sales'] = $sales;
$data[]['product'] = $product;
}
Session::flash('success', 'Sale is successfully');
return view('admin.invoice.index')->with('data', $data);
}
admin.invoice.index
#extends('layouts.master')
#section('content')
#foreach($data as $d)
{{$d['sales']}}
{{$d['product']}}
#endforeach
#endsection
My web.php or routes:
Route::resource('categories', 'CategoriesController');
Route::resource('products', 'ProductsController');
Route::resource('sales', 'SalesController');

ErrorException Undefined variable: code (View: C:\wamp\www\secureserver\app\views\emails\adminverify.blade.php)

I have been toiling around to no avail of Solutions Please help. It seems my View cannot read the $code and $user variable respectively from my Controller
Here is the part of my controller that the $code and $user Variables are been instantiated respectively:
UserController.php
public function varifyMail($code){
if(User::where('varification_code','=',$code)->update(['varification_status'=>1])){
return Redirect::route('login')
->with('success', 'Account varified.');
}else{
return Redirect::route('login')
->with('error', 'Varification Failed.Try again');
}
);
$validation = Validator::make(Input::all(),$rules);
if($validation->fails()){
return Redirect::route('login')
->with('error', 'Invalid Email Address. Try again.');
}else{
$code = str_random(25);
$userUpdate = ['recovery_code' => $code];
User::where('email','=',Input::get('email'))->update($userUpdate);
$data = ['code'=>$code];
//send mail
Mail::send('emails.recover',$data,function($message){
$message->to(Input::get('email'))->subject('Recover Your Account.');
});
return Redirect::route('login')
->with('success', 'Request Send successfully.Please Recover Your Account.');
//return User::where('email','=',Input::get('email'))->get();
}
Auth::login($user);
return View::make('users.edit')
->with('title','Update Cridentials')
->with('user',User::where('id','=',$user->id)->first());
}else{
return Redirect::route('login')
->with('error', 'Recovery Failed.Try again');
}
And this is my view:
Adminverify.blade.php
<div class="header-content"><webversion>Web Version</webversion><span class="hide"> | <preferences lang="en">Update preferences</preferences> | </span>
But whenever I try using it it get this error:
ErrorException
Undefined variable: code (View: C:\wamp\www\secureserver\app\views\emails\adminverify.blade.php)
Any Help will be highly Appreciated Thanks!
Thanks for your prompt response but it happens to be that it did not work but here is my entire Controller with the Varify changed to Verify as cadmium suggested so we can be sure what exactly could be the challenge.
class UserController extends BaseController {
private function verify($email){
$verify = User::where('email','=',$email)->first();
if(! is_null($verify)){
if($verify->role_id==2){
return $verify->distributor_approve & $verify->varification_status;
}else{
return $verify->varification_status;
}
}else{
return 0;
}
}
/**
* login page
* #return void
*/
public function login()
{
return View::make('users.login')
->with('title', 'Log in');
}
/**
* process to login a user
* #return void
*/
public function doLogin()
{
$rules = array
(
'email' => 'required|email',
'password' => 'required'
);
$validation = Validator::make(Input::all(), $rules);
if($validation->fails())
return Redirect::route('login')
->withInput()
->withErrors($validation);
else
{
$credentials = array
(
'email' => Input::get('email'),
'password' => Input::get('password')
);
if($this->verify(Input::get('email')) && Auth::attempt($credentials))
{
Session::put('role', Auth::user()->role_id);
//return User::where('id','=',Auth::user()->id)->first();
if(User::where('id','=',Auth::user()->id)->first()->first_login == 0){
return Redirect::route('info.create',[Auth::user()->id]);
}
return Redirect::intended('/');
}
else
return Redirect::route('login')
->withInput()
->with('error', 'Error in Email Address or Password.');
}
}
/**
* logout a user
* #return void
*/
function logout()
{
Auth::logout();
Session::forget('role');
return Redirect::route('login')
->with('success', 'You have been logged out.');
}
public function show(){
$pages= Page::orderby('title')->get();
if(Auth::check()){
if(Auth::user()->role_id==1){
return View::make('public.pages.admin')
->with('title', "Home");
}
}
return View::make('public.pages.show')
->with('title', "Home")
->with('pages',$pages);
}
public function register()
{
return View::make('users.register')
->with('title', 'Register');
}
public function doRegister()
{
//return Input::all();
$rules = array
(
'username' => 'required|min:3|max:15',
'email' => 'required|email|unique:users',
'password' =>'Required|Confirmed',
'password_confirmation' =>'Required',
'role' => 'Required',
'agree' => 'Required',
'recaptcha_response_field' => 'required|recaptcha'
);
$validation = Validator::make(Input::all(), $rules);
if($validation->fails())
return Redirect::route('register')
->withInput()
->withErrors($validation);
else
{
if(Input::get('role')==3){
$user = new User;
$user->user_name = Input::get('username');
$user->email = Input::get('email');
$user->password = Hash::make(Input::get('password'));
$user->role_id = Input::get('role');
$code = str_random(25);
$user->varification_code = $code;
$data = ['username'=>Input::get('username'),'code'=>$code];
Mail::send('emails.validate',$data,function($message){
$message->to(Input::get('email'))->subject('Please Verify Your Email.');
});
if($user->save())
return Redirect::route('home')
->with('success', "Verify Your Account.");
else
return Redirect::back()->withInput()->withErrors($validation)->with('error', 'Some error occured. Try again.');
}else{
$user = new User;
$user->user_name = Input::get('username');
$user->email = Input::get('email');
$user->password = Hash::make(Input::get('password'));
$user->role_id = Input::get('role');
$user->distributor_status = 1;
$code = str_random(25);
$user->varification_code = $code;
$data = ['username'=>Input::get('username'),'code'=>$code];
Mail::send('emails.validate',$data,function($message){
$message->to(Input::get('email'))->subject('Please Verify Your Email.');
});
if($user->save())
return Redirect::route('home')
->with('success', "Request Send successfully.Please Verify Your Email.");
else
return Redirect::back()->withInput()->withErrors($validation)->with('error', 'Some error occured. Try again.');
}
}
}
public function edit(){
return View::make('users.edit')
->with('title','Update Cridentials')
->with('user',User::where('id','=',Auth::user()->id)->first());
}
public function update(){
$rules = array
(
'username' => 'required|min:3|max:15',
'password' =>'Required|Confirmed',
'password_confirmation' =>'Required'
);
$validation = Validator::make(Input::all(), $rules);
if($validation->fails())
return Redirect::back()
->withInput()
->withErrors($validation);
else
{
$userUpdate = ['user_name' => Input::get('username'),
'password'=>Hash::make(Input::get('password'))
];
if(User::find(Auth::user()->id)->update($userUpdate)){
Auth::logout();
Session::forget('role');
return Redirect::route('login')
->with('success', 'Your Cridentials Have Been Changed.');
}
else
return Redirect::back()->withInput()->withErrors($validation)->with('error', 'Some error occured. Try again.');
}
}
public function verifyMail($code){
if(User::where('varification_code','=',$code)->update(['varification_status'=>1])){
return Redirect::route('login')
->with('success', 'Account varified.');
}else{
return Redirect::route('login')
->with('error', 'Varification Failed.Try again');
}
}
public function passwordRecover(){
$rules = array
(
'email' => 'required|email'
);
$validation = Validator::make(Input::all(),$rules);
if($validation->fails()){
return Redirect::route('login')
->with('error', 'Invalid Email Address. Try again.');
}else{
$code = str_random(25);
$userUpdate = ['recovery_code' => $code];
User::where('email','=',Input::get('email'))->update($userUpdate);
$data = ['code'=>$code];
//send mail
Mail::send('emails.recover',$data,function($message){
$message->to(Input::get('email'))->subject('Recover Your Account.');
});
return Redirect::route('login')
->with('success', 'Request Send successfully.Please Recover Your Account.');
//return User::where('email','=',Input::get('email'))->get();
}
}
public function mailRecover($code){
$user = User::where('recovery_code','=',$code)->first();
if(! is_null($user)){
Auth::login($user);
return View::make('users.edit')
->with('title','Update Cridentials')
->with('user',User::where('id','=',$user->id)->first());
}else{
return Redirect::route('login')
->with('error', 'Recovery Failed.Try again');
}
}
/**
* Show a page
* #param string $pageUrl
* #return void
*/
public function pages($pageUrl = 'home')
{
try
{
$page = Page::where('url', '=', $pageUrl)->firstOrFail();
/*
if($page->id == 1) $layout = 'layouts.home';
else $layout = 'layouts.default';
*/
$layout = 'layouts.default';
return View::make('public.pages.publicShow')
->with('title', "$page->title")
->with('page', $page)
->with('layout', $layout);
}
catch(ModelNotFoundException $e)
{
return "Page not found.";
}
}
Somewhere in your code you need to have View::make("adminverify"). I don't see it in the code you've posted, but it's there somewhere. You need to pass the $code value to this view, like so:
View::make("adminverify")->with("code", "some code value");
Once you do that, the $code variable will be available in the template.

Resources