how to get data from this result of query in laravel - laravel

I have written this query and i want access my user email.
The query is
$records = $this->projectRepository->with(['customer','provider'])->all();
dd($records);
foreach($records as $record) {
dd($record->provider->User->email);
}
the result of my dd($records) is as given below.i want to access highligted part.So let me know the for each loop.Whats mistake in my for each loop.I
enter image description here

Your provider relation returns an instance of your User model. So your provider and User are one and the same here. You can access the email attribute (or any other User attribute) like this:
$records = $this->projectRepository
->with(['customer','provider'])
->all();
foreach($records as $record):
// The user email
echo $record->provider->email;
// The user name
echo $record->provider->name;
endforeach

You have to give us more to work with next time. Give us an error. Give us your models. Give us something!
Now, from what I see, you need to remove the User, as the provider is of class User according to your provided dd screenshot. Thus, $record->provider->email should do the trick. Let me know if this works.

Related

How do I allow a 3rd party (twilio) access to current user account in laravel

I am making an application using laravel and twilio that gets feedback about student performance. The logic as follows.
A user, in my case the Student(called resident) logs in and uses a
web page form to send an eval request to a teacher (called
attending). This step starts a session and saves teacher info and
student info.
A random question is picked from a database and saved to the session.
The phone number of the teacher is pulled from a database and the random question is pulled from session and sent to the teacher on SMS using twilio.
The teacher responds with yes, no, or DNS (did not see) via Twilio SMS.
The teacher's response along with the student name, the teacher name and the question asked are saved to a database.
My application works up until step 5. The problem is that a new session is being started when the teacher responds via SMS. So everything after the response is saved to a new session. I can't get access to the original session. I think I need a way to automatically grant the teacher access to the student(ie. user's account). This seems to be a problem with it being a 3rd party application. Can this be done or is there another way to accomplish this?
Below is the code I am using for the response. It is not able to access the session that contains the residentName, the firstQuestion, or the attending_name data. It puts null for those values and uploads null to the database. How do I get access to the initial session in this situation?
namespace App\Http\Controllers;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Session;
use Twilio\Rest\Client;
use Twilio\Twiml;
use App\Question;
use App\Answer;
class AskFirstQuestionsController extends Controller
{
public function qOneResponse(Request $request) {
$responderNumber = $request->input('From');
session()->put('responderNumber', $responderNumber);
session()->save();
$responderAnswer = strtolower($request->input('Body'));
$residentName = session::get('residentName');
$firstQuestion = session::get('first_question');
$attending_name = session::get('attending_name');
if (strpos($responderAnswer, 'yes') !== false) {
$answer = new
Answer(['attending'=>$attending_name,'resident_name'=>$residentName,'question_body'
=>$firstQuestion, 'answer_yes'=>1]);
$answer->save();
$smsResponse = "Great! Please help us reinforce this action by providing specific feedback
to the resident about what they did. Thank You for teaching!";
} else if (strpos($responderAnswer, 'no') !== false) {
$answer = new
answer::create(['attending'=>$attending_name,'resident_name'=>$resident_name,'question_body'
=>$firstQuestion, 'answer_no'=>1]);
$answer->save();
$smsResponse = "Ugh, ok...we will work on this. If you feel comfortable, please help us by
providing specific feedback to the resident about what they need to work on. Thank You for
teaching!";
} else if (strpos($responderAnswer, 'dns') !== false) {
$answer = new
answer::create(['attending'=>$attending_name,'resident_name'=>$resident_name,'question_body'
=>$firstQuestion, 'answer_dns'=>1]);
$answer->save();
$smsResponse = "How about trying a different question?";
} else {
$smsResponse = 'Please answer yes, no or dns.';
}
return response($this->respond($smsResponse))->header('Content-Type', 'application/xml');
}
public function respond($smsResponse) {
//get responderNumber and use it below
$responderNumber = session::get('responderNumber');
$response = new Twiml();
$response->message($smsResponse, ['to' => $responderNumber]);
return $response;
}
Do I need to do some type of multiauth approach and somehow grant the teacher automatic access to the student's account (user account)? Or do I have to re-write the logic so that the response-request lifecycle closes and then try to write to the database (maybe it will then use the original session data?)? Or is there a simpler way? Please help. I have been stuck for more than a week.
Twilio developer evangelist here.
I'm not a Laravel developer, but session objects in web application frameworks like this are normally tied to a cookie that either stores the contents of the session or an ID for the session which points to the contents in a database in order to add state to a user's session within a browser.
When Twilio receives an incoming SMS message the webhook that is sent to your server is not connected to the browser session that the user is part of, so you cannot access the same data.
Instead of using the session, you should store this as part of your actual database so that you can look up the details from the database when you receive the SMS.

How can I get Joomla component parameter values?

===
UPDATE:
I think now I am literally just trying to get a database value into my component php files, but again, there seems to be very little documentation that can give an example of a function that will return this info like there is in Wordpress.
So I have a table called membersarea_countries that will have records of differnt countries I want to store values for.
I've read about JTable and other things, but how can I simply just bring back the records from this table?
$row = JTable::getInstance('membersarea_countries', 'Table', array());
But this returns a boolean of 0.
I'd really appreciate some help if anyone can.
===
I've been following what several online guides explain, which are all pretty much the same thing, but I never seem to return the values that I'm expecting.
In Components > Members Area (my component), I have a table set up to allow me to enter a record for each country, and then store a uniqueRef, signature, and URL within that record. (for GeoIP purposes).
I've created the first record, however when I try to use the following code, which the tutorials suggest, I don't see any of my fields within this:
$app = JFactory::getApplication();
$params = $app->getParams();
$uniqueRef = $params->get('uniquereference');
$signature = $params->get('signature');
This is all I see in NetBeans:
There's nothing about $app, and no sign of the fields I've got in the Joomla backend.
I don't understand what's happening, or exactly what I should be doing here. Wordpress uses a simple get_option function. Can anyone try and help me?
Below is the link to the detailed document about JTable -
https://docs.joomla.org/Using_the_JTable_class
Firstly you need to create JTable instance using below code and also change table file name to membersareacountries.php
JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_membersarea/tables');
$row = JTable::getInstance('Membersareacountries', 'Table', array());
JTable Class in this file /administrator/components/com_membersarea/tables/membersareacountries.php-
<?php
defined('_JEXEC') or die();
class TableMembersareacountries extends JTable
{
public function __construct($db)
{
parent::__construct( '#__membersarea_countrie', 'id', $db );
}
}
Then you can use load method to get any records. This accepts primary key value of that table -
$id = 1;//change id as per your record
$row->load($id);
//read data
echo $row->id;
echo $row->title;

Laravel Auth User

In my controller i'm doing
$user = Auth:user()->get();
dd($user);
This is giving me the list of all users from my database.
why?
The other answers either explain how to solve your problem but not properly why this happens.
The laravel documentation states (source):
The get method returns an Illuminate\Support\Collection containing the results where each result is an instance of the PHP StdClass object.
With the full documentation found here, with API references here.
In essence, the get function here returns a collection and not the User object. The get method on an QueryBuilder executes a select statement.
With the following snippet we can see what queries get executed.
DB::enableQueryLog();
Auth::user()->get();
dump(DB::getQueryLog());
This will output:
DB::enableQueryLog();
Auth::user()->where('id', 1)->get();
dump(DB::getQueryLog());
This will output:
The first query will indeed output the expected user, the second query will grab the user class from the Auth::user() and select all rows from that table.
When we execute the 3rd and 4th query we can see that we once more first get the expected user, the 4th query however does also get a user (in this case the user with id 1). This is due too the where and not the Auth::user().
What we can conclude from these results is that the get takes into account all query builder functions but not the parameters of the supplied class.
If you use a get on an object it will only take into account the Class of that Object.
As too solve your problem the other questions where correct and you can use:
$user = Auth::user();
To fetch the user.
Because get return collection
Laravel Doc
Just remove get() to get single user data
$user = Auth:user();
dd($user);
in this case get() method return user collection object
You can auth user data by :
$user = Auth::user(); instead of using get();
Your user id is: {{ $user->id }}
Your first name is: {{ $user->first_name }}
Your last name is: {{ $user->last_name }}
return User::where('id', auth()->id())->with(['something'])->first()

If else statement based on database row

Im having a bit of trouble figuring out how to interact with the database in Laravel.
Im writing a small app, and its come to the point where I need to enter, check and return results.
I have followed the docs to setup authentication and now I can have users log in and out.
So what I want to do is store letters.
I have a table called letters.
A user can write as many letters as they want, their user ID is stored in the letters table in the column called userID
When a user clicks on the 'Letters' navigation item, it takes them to the
Route::get('letters')..........
When it loads the view, if there are no letters in the database I want it to say 'No previous letters' .. if there is some letters in the DB, I just want it to say 'Welcome back'
I cant find how or where to achieve this.
I'm hoping someone can help me out and give me a bit of a hand writing the code as I cant find anything in the docs.
You need to do this in a controller.
Route::get('letters', ['uses' => 'LettersController#index']);
And then in your letters controller
public function index()
{
// Grab letters for the user. You need to be sure that the user is logged in
$letters = Letter::forUser(Auth::user())->get();
$data = [
'letters' => $letters
];
// You will be able to call $letters->count() in your view
return View::make('letters.index', $data);
}
In your letter Model
public function scopeForUser(User $u)
{
return $query->where('user_id', '=', $u->id);
}

Magento returning incorrect customer data on frontend pages

isn't this the right method to get Name of logged in customer?
<?php echo Mage::helper('customer')->getCustomer()->getName(); ?>
I have a website with live chat functionality. Yesterday I have been asked to pass email address and the name of the logged into the user into the Javascript Tracking variable code placed in the head section of the website. So that the operators could see who is on the website and whom are they talking to without any need to ask about their information.
So I passed the information from Magento into the Javascript code but now I see this very strange thing happening. For example,
If I am logged in with credentials Name = John Email =
john12#yahoo.com
Then This name and email variable values are changing with the change of pages. For example if I click on any product page the variable values which I am passing changes to some other user's information.
Name becomes Ricky Email becomes ricky23#gmail.com
this variable values are kept on changing back to john and from john to something else with the change of pages. So operator does not have any idea whom are they talking because the values are kept on changing. Also, user ricky or who ever it changes to also exist in the database. so it is picking up random person from the database.
This is what i did to pass the code to javascript. Please let me know if that is not the right code to pass the information. Please check the php code I am using to fetch information from Magento. Roughly, I receive incorrect value once in 5 times. Please provide some assistance. Thanks in advance.
<?php
$customer = Mage::getSingleton('customer/session')->getCustomer();
$email = $customer->getEmail();
$firstname = $customer->getFirstname();
$lastname= $customer->getLastname();
$name = $firstname . ' ' . $lastname;
?>
<script type="text/javascript">
if (typeof(lpMTagConfig) == "undefined"){ lpMTagConfig = {};}
if (typeof(lpMTagConfig.visitorVar) == "undefined"){ lpMTagConfig.visitorVar = [];}
lpMTagConfig.visitorVar[lpMTagConfig.visitorVar.length] = 'Email=<?php echo $email; ?>';
lpMTagConfig.visitorVar[lpMTagConfig.visitorVar.length] = 'Name=<?php echo $name; ?>';
</script>
I'm also attaching a snap shot
I'd be interested to hear how you're adding this code to the page? Is it in it's own block, or are you adding it to footer.phtml, or similar? If your adding to an existing block be sure to check the block caching settings of that template.
To confirm the caching hypothesis I'd ask the following:
Do you get the same name, all the time, on the same page? When you refresh the page, do you get the same name and email in the Javascript?
Does the problem persist with caching disabled?
This doesn't sound like a singleton problem at all. Each execution of the PHP script is isolated from the others, serving one page request. There's no chance of another customer's object moving between invokations of the script.
It is a matter of understanding the singleton pattern. If you call your code twice:
$customer_1 = Mage::helper('customer')->getCustomer()->getName();
$customer_2 = Mage::helper('customer')->getCustomer()->getName();
you get two different instances of the object. But... if one of them has already implemented a singleton pattern in its constructor or has implemented a singleton getInstance then both objects will actually point to the same thing.
Looking at the customer/helper/Data.php code you can see the function
public function getCustomer()
{
if (empty($this->_customer)) {
$this->_customer = Mage::getSingleton('customer/session')->getCustomer();
}
return $this->_customer;
}
That means that in one of the cases singleton is already implemented/called and in other one - not as the property is already set.
The correct way to work with quote/customer/cart in order to get always the correct data is always to use the singleton pattern.
So using this:
$customer = Mage::getSingleton('customer/session')->getCustomer();
always guarantee that you get the correct customer in that session. And as may be you know singleton pattern is based on registry pattern in app/Mage.php:
public static function getSingleton($modelClass='', array $arguments=array())
{
$registryKey = '_singleton/'.$modelClass;
if (!self::registry($registryKey)) {
self::register($registryKey, self::getModel($modelClass, $arguments));
}
return self::registry($registryKey);
}
and looking at app/Mage.php:
public static function register($key, $value, $graceful = false)
{
if (isset(self::$_registry[$key])) {
if ($graceful) {
return;
}
self::throwException('Mage registry key "'.$key.'" already exists');
}
self::$_registry[$key] = $value;
}
...
public static function registry($key)
{
if (isset(self::$_registry[$key])) {
return self::$_registry[$key];
}
return null;
}
you can see that Magento checks is it is already set. If so, Magento will either throw an Exception, which is the default behavior or return null.
Hope this will help you to understand the issue you face.
I have sorted this out. I have moved the code from footer.phtml to head.phtml and it's working fine now.Values are not changing anymore. If anyone know the logic behind please post and I will change my answer. So far this is working.

Resources