Voyager - Can we send e-mail when admin add user? - laravel

I am trying send information e-mail to user when admin add user. But i don't know how can i intervene the Userpage in Adminpanel?
For example: Welcome "$user->name", your username is "$user->username" and your password is "$user->password".
I think about a lot. But can't progress. Still can not send any email. Do we have a way to make this e-mailing system easier in voyager tables?
edit: Added Registercontroller
public function register(Request $request)
{
$this->validation($request);
$customer = new Customer();
$customer->name = $request->name;
$customer->surname = $request->surname;
$customer->phone = $request->phone;
$customer->email = $request->email;
$customer->password = bcrypt($request->password);
$customer->description = $request->password;
$customer->save();
Auth::guard('customer')->login($customer);
Session::flash('success', __('messages.success'));
return redirect('/');
edit: Added CustomerObserve.php
<?php
namespace App\Helper\Observers;
use App\Customer;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Mail;
class CustomerObserve implements ShouldQueue
{
public function created()
{
$customer = Customer::latest();
Mail::send('user_login_informations', ['customer' => $customer], function($message) use($customer) {
$message->to($customer->email, $customer->name)
->subject('account update');
})->delay(30);
}
}

create an email template in view folder
email.blade.php
#section('content')
<h2>Hello {{ ucfirst($customer->name) }},</h2>
<p>
Your email '{{ $customer->email }}' and password {{ $customer->password }}.
</p>
#stop
Reviewer controller
$this->validation($request);
$customer = new Customer();
$customer->name = $request->name;
$customer->surname = $request->surname;
$customer->phone = $request->phone;
$customer->email = $request->email;
$customer->password = bcrypt($request->password);
$customer->description = $request->password;
$customer->save();
Auth::guard('customer')->login($customer);
Session::flash('success', __('messages.success'));
Mail::send('email', ['customer' => $customer], function($message) use($customer) {
$message->to($customer->email, $customer->name)
->subject('account update');
});
return redirect('/');

Related

Laravel Date assign errorr

I have small problem in app. Backend is Laravel and Front end is Nuxtjs.
When User registered on app,then users must be wait antill Administartor approved.
When Admin approved this user we give them 3 months subscription.
In my code this part is not working.
$user->activated_at = now();
$user->activated_at = date('Y-m-d H:i');
{
$user = User::find($id);
if (is_null($user)) {
return $this->sendError('admin_messages.user_not_found');
}
$user->status = User::ACTIVE;
$user->activated_at = now();
$user->activated_at = date('Y-m-d H:i');
dd($user->activated_at);
$user->save();
Mail::to($user->email)->queue(new ApproveNotificationMail($user));
return $this->sendResponse('admin_messages.user_activated');
}
$user->activated_at = \Carbon\Carbon::now()->format('Y-m-d H:i');
You can use mutator in your User model, to force activated_at format:
public function setActivatedAtAttribute( $value ) {
$this->attributes['activated_at'] = (new Carbon($value))->format('Y-m-d H:i');
}
You can define a format for date columns using:
protected $dateFormat = 'Y-m-d H:i';
Note that you can directly use:
$user->activated_at = \Carbon\Carbon::now()->format('Y-m-d H:i');

How to automatic slug when i press the submit button

I want to create slug by using value of $item->name = $request->input('name'); before $item->save();
//use Illuminate\Support\Str;
private function saveItem(Request $request, $item){
$item->name = $request->input('name');
$item->slug = Str::title($item->name,"-");
$item->save();
}
When the $item->name = $request->input('name') value is Hello World,
Then after slug the output will be Hello-World
Please help.
You can generate a slug using the Str::slug() method:
private function saveItem(Request $request, $item){
$item->name = $request->input('name');
$item->slug = Str::slug($item->name);
$item->save();
}

Paypal integration controller not working in Laravel

I create an account at paypal to test in my app.
composer require paypal/rest-api-sdk-php
Added the client ID and secret to the .env
This is what I currently have in my view
#if ($message = Session::get('success'))
<div class="w3-panel w3-green w3-display-container">
<span onclick="this.parentElement.style.display='none'"
class="w3-button w3-green w3-large w3-display-topright">×</span>
<p>{!! $message !!}</p>
</div>
<?php Session::forget('success');?>
#endif
#if ($message = Session::get('error'))
<div class="w3-panel w3-red w3-display-container">
<span onclick="this.parentElement.style.display='none'"
class="w3-button w3-red w3-large w3-display-topright">×</span>
<p>{!! $message !!}</p>
</div>
<?php Session::forget('error');?>
#endif
<form class="w3-container w3-display-middle w3-card-4 " method="POST" id="payment-form" action="{!! URL::to('paypal') !!}">
{{ csrf_field() }}
<h2 class="w3-text-blue">Payment Form</h2>
<p>
<label class="w3-text-blue"><b>Enter Amount</b></label>
<input class="w3-input w3-border" name="amount" type="text"></p>
<button class="w3-btn w3-blue">Pay with PayPal</button></p>
</form>
My PaymentController looks like this:
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Session;
use Illuminate\Http\Request;
use PayPal\Api\Amount;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Payer;
use PayPal\Api\Transaction;
use PayPal\Api\Payment;
use PayPal\Api\Details;
use PayPal\Api\ChargeModel;
use PayPal\Api\Currency;
use PayPal\Api\MerchantPreferences;
use PayPal\Api\PaymentDefinition;
use PayPal\Api\Plan;
use PayPal\Api\Patch;
use PayPal\Api\PatchRequest;
use PayPal\Common\PayPalModel;
use PayPal\Rest\ApiContext;
use PayPal\Auth\OAuthTokenCredential;
use PayPal\Api\RedirectUrls;
use PayPal\Api\PaymentExecution;
use URL;
use Redirect;
use Illuminate\Support\Facades\Input;
class PaymentController extends Controller
{
private $apiContext;
private $mode;
private $client_id;
private $secret;
public function __construct()
{
/** PayPal api context **/
$paypal_conf = \Config::get('paypal');
$this->_api_context = new ApiContext(new OAuthTokenCredential(
$paypal_conf['client_id'],
$paypal_conf['secret'])
);
$this->_api_context->setConfig($paypal_conf['settings']);
}
public function payWithpaypal(Request $request){
$payer = new Payer();
$payer->setPaymentMethod('paypal');
$item_1 = new Item();
$item_1->setName('Item 1') /** item name **/
->setCurrency('USD')
->setQuantity(1)
->setPrice($request->get('amount')); /** unit price **/
$item_list = new ItemList();
$item_list->setItems(array($item_1));
$amount = new Amount();
$amount->setCurrency('USD')
->setTotal($request->get('amount'));
$transaction = new Transaction();
$transaction->setAmount($amount)
->setItemList($item_list)
->setDescription('Your transaction description');
$redirect_urls = new RedirectUrls();
$redirect_urls->setReturnUrl(URL::route('status')) /** Specify return URL **/
->setCancelUrl(URL::route('status'));
$payment = new Payment();
$payment->setIntent('Sale')
->setPayer($payer)
->setRedirectUrls($redirect_urls)
->setTransactions(array($transaction));
/** dd($payment->create($this->_api_context));exit; **/
try {
$payment->create($this->_api_context);
} catch (\PayPal\Exception\PPConnectionException $ex) {
if (\Config::get('app.debug')) {
\Session::put('error', 'Connection timeout');
return Redirect::route('paywithpaypal');
} else {
\Session::put('error', 'Some error occur, sorry for inconvenient');
return Redirect::route('paywithpaypal');
}
}
foreach ($payment->getLinks() as $link) {
if ($link->getRel() == 'approval_url') {
$redirect_url = $link->getHref();
break;
}
}
/** add payment ID to session **/
Session::put('paypal_payment_id', $payment->getId());
if (isset($redirect_url)) {
/** redirect to paypal **/
return Redirect::away($redirect_url);
}
\Session::put('error', 'Unknown error occurred');
return Redirect::route('paywithpaypal');
}
public function getPaymentStatus(){
/** Get the payment ID before session clear **/
$payment_id = Session::get('paypal_payment_id');
/** clear the session payment ID **/
Session::forget('paypal_payment_id');
if (empty(Input::get('PayerID')) || empty(Input::get('token'))) {
\Session::put('error', 'Payment failed');
return Redirect::route('/');
}
$payment = Payment::get($payment_id, $this->_api_context);
$execution = new PaymentExecution();
$execution->setPayerId(Input::get('PayerID'));
/**Execute the payment **/
$result = $payment->execute($execution, $this->_api_context);
if ($result->getState() == 'approved') {
/*************************************************
PAYMENT SUCCESSFULL - DO THE REST HERE
/************************************************/
\Session::put('success', 'Payment success');
return Redirect::route('/');
}
\Session::put('error', 'Payment failed');
return Redirect::route('/');
}
}
So now when I enter an amount and try to pay, I get the following error:
Argument 1 passed to PayPal\Rest\ApiContext::setConfig() must be of the type array, null given, called in C:\xampp\htdocs\owlproperty\app\Http\Controllers\PaymentController.php on line 47
I created the paypal file under the config folder and that looks like this:
<?php
return [
'client_id' => env('PAYPAL_CLIENT_ID',''),
'secret' => env('PAYPAL_SECRET',''),
'settings' => array(
'mode' => env('PAYPAL_MODE','sandbox'),
'http.ConnectionTimeOut' => 30,
'log.LogEnabled' => true,
'log.FileName' => storage_path() . '/logs/paypal.log',
'log.LogLevel' => 'ERROR'
),
];
Anything I could have possibly done wrong?
You are not loading the config file correctly:
From the documentation:
The configuration values may be accessed using "dot" syntax, which
includes the name of the file and option you wish to access.
Assuming your confile file is named paypal.php, use this in the constructor:
public function __construct()
{
/** PayPal api context **/
$settings = config('paypal.settings');
$client_id = config('paypal.client_id');
$secret = config('paypal.secret');
$this->_api_context = new ApiContext(new OAuthTokenCredential(
$client_id,
$secret)
);
$this->_api_context->setConfig($settings);
}

Codeigniter User's Data

Hi guys I have a User controller and User_model model. I want to be able to retrieve and display a logged in users email and phone number from the database to a view after the user is logged in. any idea how I could go about this would be appreciated and if codes could be written to demonstrate I would be very happy.
MODEL
public function login($username, $password){
//validation
$this->db->select('id, email, username');
$this->db->where('username', $username);
$this->db->where('password', $password);
$this->db->where('status', 1);
$result = $this->db->get('users');
if($result->num_rows() == 1){
return $result->row(0)->id;
} else {
return FALSE;
}
}
public function get_user($username){
$this->db->where('username', $username);
$query = $this->db->get('users');
return $query->result();
}
CONTROLLER:
public function login(){
$data['title'] = 'Login';
$this->form_validation-> set_rules('username', 'Username', 'required');
$this->form_validation-> set_rules('password', 'Password', 'required');
if($this->form_validation->run() === FALSE){
$this->load->view('templates/header');
$this->load->view('users/login', $data);
$this->load->view('templates/footer');
} else {
// fetching user
$username = $this->input->post('username');
//Encrypted password
$password = md5($this->input->post('password'));
//login user
$user_id = $this->user_model->login($username, $password);
if($user_id){
//creating session
$user_data = array(
'user_id' => $user_id,
'username' => $username,
'logged_in' => TRUE,
);
$this->session->set_userdata('user_data',$user_data);
// Set message to be sent
$this->session->set_flashdata('user_login', 'Welcome');
redirect('posts');
} else {
// Set message to be sent
$this->session->set_flashdata('login_fail', 'Login Failed');
redirect('users/login');
}
}
}
public function get_user()
{
if($this->session->userdata('logged_in')){
$username = $this->session->userdata('username');
$data['results'] = $this->user_model->get_user($username);
$this->load->view('templates/header');
$this->load->view('users/login', $data);
$this->load->view('templates/footer');
}
}
There is basic problem in your Controller
Session Data Problem: In your Controller you storing all array data in CodeIgniter Session:
the 'user_data' would work like array key, and all other array will be assign as keys data;
$this->session->set_userdata('user_data', $user_data);
and you retrieving/checking the session data by using $this->session->userdata('logged_in') and $this->session->userdata('username'), It's wrong my friend. You can get user data session by $this->session->userdata('user_data')['username'] or $this->session->userdata['user_data']['username'] ...
Because the session would be like;
Array
(
[__ci_last_regenerate] => 1499791562
// This is the array key 'user_data' where your array data stores
[user_data] => Array
(
[user_id] => 1
[username] => scott
[email] => scott.dimon#example.com
[phone_number] => 1234567890
[first_name] => Scott
[logged_in] => 1
)
)
So, you have to have use 'user_data' with session to get your data
One thing I would like to share with everyone, Always Read The Docs and manual Carefully. Believe me if you read before the start, your code would be more nicer and cleaner... Ha ha ha ha ha.. ;) :|
When you login if you set the users_id in session you can get the information like
Read manual also
https://www.codeigniter.com/user_guide/database/results.html#result-rows
https://www.codeigniter.com/user_guide/general/views.html#adding-dynamic-data-to-the-view
Make sure you autoload session, and database.
Examples ONLY below.
Filename: User_model.php
class User_model extends CI_Model {
public function get_user($id)
{
$this->db->where('user_id', $id);
$user_query = $this->db->get('yourtable');
return $user_query->row_array();
}
}
Filename: Dashboard.php
Controller
<?php
class Dashboard extends CI_Controller {
public function __construct()
{
parent::__construct();
if (!$this->session->userdata('user_id'))
{
redirect('logoutcontroller');
}
$this->load->model('user_model');
}
public function index()
{
$userdata = $this->user_model->get_user($this->session->userdata('user_id'));
/** You can use what you want example
$data['email'] = $userdata['email'];
**/
$data['username'] = $userdata['username'];
$this->load->view('some_view', $data);
}
}
View
<?php echo $username;?>
You can use session to carry the logged in user detail.
This is your model code:
//In your model
$query = $this->db
->select('id,email,phone')
->where(['username' => $username, 'password' => $password])
->where('status','1')
->get('users');
$user_data = $query->row_array();
if (!empty($user_data)) {
return $user_data;
} else {
return FALSE;
}
In side the controller where you get the user data if username & password is correct. Here you can put the user data on session:
//In Side Controller
$user_data = $this->user_model->login($username, $password);
if(isset($user_data) && !empty($user_data)){
// you can directly add the `$user_data` to the session as given billow.
// set user data in session
$this->session->set_userdata('user_data', $user_data);
Now after putting a data on session you can retrive it any where, on any view or in side morel, controller.
//retrive the user data in any view
//To echo in view Inside your view code.
<?php
$session_data = $this->session->userdata('user_data');
$user_email = $session_data['email'];
$user_phone = $session_data['phone'];
$user_id = $session_data['id'];
?>
<?= $user_phone ?> OR <?php echo $user_phone; ?>
<?= $user_email ?> OR <?php echo $user_email; ?>
On Your $this->load->view('users/login', $data); this view. Where the HTML & PHP code placed.
Example:
<html>
// Your View Page
</body>
<?php
$session_data = $this->session->userdata('user_data');
$user_email = $session_data['email'];
$user_phone = $session_data['phone'];
$user_id = $session_data['id'];
?>
<h1> Logged In User Email: <?= $user_email ?> </h1>
<h1> Logged In User Phone: <?= $user_phone ?> </h1>
<body>
</html>
Note: Once You save the user data inside the session then you don't need to pass that data to the view form controller. You just need to echo it where you need that.
You need to load session library first. like
$this->load->library('session');
Then after you can save your data into session like,
$newdata = array(
'username' => 'johndoe',
'email' => 'johndoe#some-site.com',
'logged_in' => TRUE
);
$this->session->set_userdata($newdata);
Then where ever you require at controller you can retrive session data like,
$data['session_data'] = $this->session->all_userdata();
and then pass to your view,
$this->load->view('data', $data);
and then access that data into your view with the key,
<?= $session_data['username']; ?>
I hope it helps,
Does this answer your question?
public function login($username, $password){
$db = $this->db;
//validation
$db->select('id, email, username');
$db->where('username', $username);
$db->where('password', $password);
$db->where('status', 1);
$result = $db->get('users')->row_array();
return empty($result['id']) ? false : $result['id'];
}
With a unique index on username you won't need to check the number of rows as it will be limited to 1.
if($user_id){
//creating session
$user_data = array(
'user_id' => $user_id,
'username' => $username,
'logged_in' => TRUE,
);
$this->session->set_userdata($user_data);
// Set message to be sent
$data['session_data'] = $this->session->all_userdata();
$this->session->set_flashdata('user_login', 'Welcome');
$this->load->view('posts', $data);
//redirect('posts');
}
else {
// Set message to be sent
$this->session->set_flashdata('login_fail', 'Login Failed');
redirect('users/login');
}
}
at the view,
<?php print_r($session_data); ?>
if you get your session data into print,
you can display it like,
<?= $session_data['user_id']; ?>
****Modal**
//user login**
function userlogin($data)
{
$condition = "username =" . "'" . $data['username'] . "' AND " . "password =" . "'" . $data['password'] . "' AND " . "status = '1'";
$this->db->select("*");
$this->db->from("user");
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1)
{
return $query->result();
}
else {
return false;
}
}
And in your Controller check
if($this->modal_name->login()==false)
{
//redirect user to login page
}
else
{
$data['details'] = $this->modal_name->login();
$this->load->view("post",$data);
}
View
foreach($details as $detail)
{
echo $detail->id;
echo $detail->username;
}

Joomla 2.5+: Creating an Account and Log in within the same Controller Call

I have created a from with a user registration. When processing the form within the controller, I want the user to be logged in afterwards. Account creation works fine, but logging right afterwards fails:
function processForm($username,$first_name,$last_name,$email,$password,$groups) {
jimport('joomla.user.helper');
$app = JFactory::getApplication('site');
$user = new JUser();
$b= array();
$user->bind($b);
$user->username = $username;
$user->name = $first_name." ".$last_name;
$user->set('id',0);
$date =date("Y-m-d H:i:s");
$user->set('registerDate', $date);
$user->email = $email;
$user->set('password',JUserHelper::getCryptedPassword($password,JUserHelper::getSalt()));
$user->set('block', '0');
$user->save();
foreach ($groups as $group) {
JUserHelper::addUserToGroup($user->id, $group);
}
$app->login(array("username"=>$username,"password"=>$password));
}
Any idea?

Resources