I want to link a record of type Person to Customer, because I want to create a customer using the same record of type person, keeping both records the same but with different profiles, but I find the following problem in my code:
Error
Call to undefined method App\Models\Roles::intersect()
store() method in CustomerController.php
public function store(CustomerRequest $customerRequest)
{
$role = Roles::where('name', 'Customer')->first();
$customer = User::where('cpf', $customerRequest->cpf)->first();
if ($customer->hasRole($role)) {
return back()->with('msg_erro', "This user is already a customer profile.");
} else {
$customer->syncRoles([$role->id]);
}
}
How can I fix this problem?
Related
public function addContact()
{
if (!$this->validate()) {
return null;
}
$model = new ContactForm();
foreach (['name', 'email', 'subject', 'body'] as $property) {
$model->$property = $this->$property;
}
return $model->save();
}
I get this error:
Calling unknown method: frontend\models\ContactForm::save()
the var_dump is working properly.
the save method return this error [save method .
This is the complete model rules :
rules model
and this is the rest of the model code :
rest of model
Could someone tell me what I'm getting wrong?
As Sfili_81 already mentioned you have to extend ActiveRecord instead of Model to be able call the save method. But that only makes sense if you want to save the data to a database.
You can use the default logic of the yii2-app-basic to send the data submitted via ContactForm to a configured admin via email. To do so you just have to call the contact method of ContactForm.
// SiteController::actionContact
$model = new ContactForm();
if ($model->load(Yii::$app->request->post()) && $model->contact(Yii::$app->params['adminEmail'])) {
Yii::$app->session->setFlash('contactFormSubmitted');
return $this->refresh();
}
If you want to receive real emails you also have to set the useFileTransport property of the mailer component to false (in config/web.php), otherwise every mail gets saved to runtime/mail.
I'm currently creating a basic inbox for a private messaging system which only displays the users which the logged in user has been in contact with if messages between the user and recipient exist. (Similar to how your standard instant messenger works)
The way I am getting this list is to check the messages table to see if any messages between the two users exist. If it does then list this in the inbox but since there will be many messages between the user, I am using a Laravel collection and the unique function to only display a recipient once. The user then can click on this recipient to see the message thread.
The issue I am having with is being able to sort this list by the latest message (e.g. sort by created_at)
How am I able to order this in order of the latest entry so that the most recent messages display at the top of the list in the inbox. Here is the code I using in my controller to get the list of recipients and attempt to sort by latest message:
$messages = collect(Message::where('recipient_id', $user)->orderBy('created_at', 'desc')->get());
$messagesUnique = $messages->sortBy('created_at')->unique('sender_id');
$messagesUnique->values()->all();
Thanks
Define your relationships:
class Message extends Model
{
public function sender()
{
return $this->belongsTo(User::class, 'sender_id');
}
public function recipient()
{
return $this->belongsTo(User::class, 'recipient_id');
}
}
In the User model:
class User extends Authenticable
{
public function received()
{
return $this->hasMany(Message::class, 'recipient_id')->latest();
}
public function sent()
{
return $this->hasMany(Message::class, 'sender_id')->latest();
}
}
Then for retrieving the messages:
$user = Auth::user();
$messages = $user->received->unique('sender_id');
$sent = $user->sent->unique('recipient_id');
I am working on an application where users can register after payment, below is my create method in RegisterController
protected function create(array $data)
{
$payment = $this->MakePayment($data);
if($payment->error)
{
flash($payment->error, 'error')->important();
redirect()->route('register');
}
else
{
//create user and return it
return $user;
}
}
but I get exception instead of returning back
(1/1) FatalThrowableError
Type error: Argument 1 passed to Illuminate\Auth\SessionGuard::login() must be an instance of Illuminate\Contracts\Auth\Authenticatable, null given, called in /home/tariqmahmood/www/local.referralfactorypro.com/vendor/laravel/framework/src/Illuminate/Foundation/Auth/RegistersUsers.php on line 35
Also, I have tried exit() after the redirect, it takes back to register route but an empty screen. Can anyone please let me know what I am doing wrong.
Try this:
$authUser = //create user into db (i.e user::insert('userData'))
Auth::login($authUser, true);
return redirect('youtRedirectUrl');
I am trying to do database login for a YII app, and I am getting this error. Here is my code:
<?php
/**
* UserIdentity represents the data needed to identity a user.
* It contains the authentication method that checks if the provided
* data can identity the user.
*/
class UserIdentity extends CUserIdentity
{
/**
* Authenticates a user.
* The example implementation makes sure if the username and password
* are both 'demo'.
* In practical applications, this should be changed to authenticate
* against some persistent user identity storage (e.g. database).
* #return boolean whether authentication succeeds.
*/
private $_id;
public function authenticate()
{
// $users=array(
// // username => password
// 'username'=>'password',
// );
// if(!isset($users[$this->username]))
// $this->errorCode=self::ERROR_USERNAME_INVALID;
// elseif($users[$this->username]!==$this->password)
// $this->errorCode=self::ERROR_PASSWORD_INVALID;
// else
// $this->errorCode=self::ERROR_NONE;
// return !$this->errorCode;
$record=User::model()->findByAttributes(array('username'=>$this->username));
print_r($record);
echo ($this->password);
echo ($record->password);
if($record===null)
$this->errorCode=self::ERROR_USERNAME_INVALID;
else if($record->password!==$this->password)
$this->errorCode=self::ERROR_PASSWORD_INVALID;
else
{
$this->_id=$record->id;
$this->setState('title', $record->title);
$this->errorCode=self::ERROR_NONE;
}
return !$this->errorCode;
}
public function getId()
{
return $this->_id;
}
}
Here is the stack trace:
As a note, I have tried to remove the $this->setState('title', $record->title); code, but that just caused another error. I have looked at the values of the User, and there is no title, I thought that might be what is causing the error, but like I said, when I remove the call, I get another error:
Fatal error: Call to a member function getId() on a non-object in
/home/fredgran/public_html/yii/framework/web/auth/CWebUser.php on line
229
remove print_r($record);
echo ($this->password);
echo ($record->password);
and change line 44 to
if(isset($record->title))
$this->setState('title', $record->title);
error "Call to a member function getId() on a non-object" is because calling Yii::app()->user->id;
Please copy your User model if the above fix is not working
The solution is very simple. This part of the code causes it.
else
{
$this->_id=$record->id;
$this->setState('title', $record->title);
$this->errorCode=self::ERROR_NONE;
}
Make sure you have a column called "title" in your user table or whatever the table that your user model refers to.
With this line,
$this->setState('title', $record->title);
you are trying to create a session variable called "title" and assign user record's title column value.
This is a example of how to set a session and retrieve it in yii.
Yii::app()->user->setState('username', $record->username); // define
Yii::app()->user->username // retrieve, can be access anywhere in the system
Read here for more : http://www.yiiframework.com/doc/api/1.1/CWebUser#setState-detail
Hope this helps.
Observe the stack trace in errors (Attached sceen-shot)
CActiveRecord->__get("title")
The meaning of this error is "You are accessing the the property which is not defined in the Model". ie, your User table does not have the column title.
Please print and check the $record object. Also check Typo error to track the error.
You are not defining title attribute in your database. But, if you want to make a login task, just try this:
else
{
$this->_id=$record->id;
//$this->setState('title', $record->title);
$this->username = $record->username; //try this code
$this->errorCode=self::ERROR_NONE;
}
CMIIW
There is no "title" field in database for user table ... you are trying to use that as $record->title so you are getting this error.
I want to access the id of currently logged in user
My beforeDelete() function in /app/models/course.php:
function beforeDelete()
{
// Some code
// code also sets value of $uid2
$uid = $this->Auth->user('id'); //this is line 86 in course.php
if ($uid2 == $uid) {
return true;
}
else {
return false;
}
}
But during execution, I get the following error:
Notice (8): Undefined property: Course::$Auth [APP/models/course.php, line 86]
Fatal error: Call to a member function user() on a non-object in /var/www/some_path/app/models/course.php on line 86
Please suggest..
Pass the id of the current logged in user with the data to the model from the controller.
$this->Model->data[$this->Model->alias]['user_id'] = $this->Auth->user('id');
In your beforeDelete() callback you can access it
$this->data[$this->alias]['user_id']
and do whatever you want there. I could give you further advice but your question is, to be honest, not very informative. Please be more specific about your goal in the future.