I am trying to do the following:
$org = Organization::first();
$user = Auth::user();
$org->owner()->save($user);
return $org;
My returned values are:
{"_id":"55f333759a370912040041c8",
"name":"Beta Productions",
"updated_at":"2015-09-11 20:03:01",
"created_at":"2015-09-11 20:03:01"}
If I try to return $org->owner, I don't get anything.
Here is my organization class:
<?php
namespace App;
use Jenssegers\Mongodb\Model as Model;
class Organization extends Model
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['name'];
public function owner()
{
return $this->embedsOne('App\User');
}
}
Any thoughts?
Related
I am having trouble getting my new subscription to be updated in MongoDB Database. Im using Laravel Cashier, Stripe, and Jenssegers MongoDB.
In the stripe dashboard, users have been successfully added as customers and subscribers.
Here is the ERROR:
[23:24:17] LOG.error: Call to a member function prepare() on null
{"userId":"4ec1b45d36623t2269477d0...
Here is where the ERROR lives:
return true;
}
$statement = $this->getPdo()->prepare($query);
$this->bindValues($statement, $this->prepareBindings($bindings));
Here is my controller:
namespace App\Http\Controllers;
use App\Plan;
use App\User;
use Exception;
use Illuminate\Http\Request;
class CheckoutController extends Controller
{
/**
* The collection name
*
* #var array
*/
public function checkout($plan_id)
{
$plan = Plan::findOrFail($plan_id);
$intent = auth()->user()->createSetupIntent();
return view('billing.checkout', compact('plan', 'intent'));
}
public function process(Request $request)
{
$plan = Plan::findOrFail($request->input('billing_plan_id'));
try {
auth()->user()->newSubscription($plan->name, $plan->stripe_plan_id)-
>create($request->input('payment-method'));
return redirect()->route('billing')->withMessage('Subscribed Successfully');
} catch (Exception $e) {
return redirect()->back()->withError($e->getMessage());
}
}
Here is My User Model:
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;
use Jenssegers\Mongodb\Auth\User as Authenticatable;
use Laravel\Cashier\Billable;
use Illuminate\Foundation\Auth;
class User extends Authenticatable
{
use Billable, Notifiable;
protected $connection = 'mongodb';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'username', 'password', 'phone', 'last_login_at',
'last_login_ip',
];
/**
* The collection name
*
* #var array
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $dates = ['deleted_at'];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Here is My Plan Model:
namespace App;
use Jenssegers\Mongodb\Eloquent\Model;
/**
* #method static findOrFail($plan_id)
*/
class Plan extends Model
{
protected $fillable = [
'name',
'price',
'stripe_plan_id'
];
}
Here is my Subscription Migration:
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Migrations\Migration;
use Jenssegers\Mongodb\Schema\Blueprint;
class CreateSubscriptionsTable extends Migration
{
/**
* The name of the database connection to use.
*
* #var string
*/
protected $connection = 'mongodb';
public function up()
{
Schema::create('subscriptions', function (Blueprint $collection) {
$collection->bigIncrements('id');
$collection->unsignedBigInteger('userid');
$collection->string('name');
$collection->string('stripe_id');
$collection->string('stripe_status');
$collection->string('stripe_plan')->nullable()->change();
$collection->integer('quantity')->nullable()->change();
$collection->timestamp('trial_ends_at')->nullable();
$collection->timestamp('ends_at')->nullable();
$collection->timestamps();
$collection->index(['user_id', 'stripe_status']);
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('subscriptions');
}
}
Please help me figure out the source of this issue and how to solve it.
Make sure your model (i'm guessing it's a model but you didn't mention / show it) that is calling $this->getPdo() is extending Jenssegers eloquent model class and not Laravels.
For example:
Replace
class MyModel extends Model
With
class MyModel extends \Jenssegers\Mongodb\Eloquent\Model
Partial Solution:
Although I am getting the same error below
"Call to a member function prepare() on null {"userId":"4ec1b45d36623t2269477d0...".
In order to get the Subscription to update in the database I went into the Subscription.php file in Cashier and I replaced
use Illuminate\Database\Eloquent\Model;
with
use Jenssegers\Mongodb\Eloquent\Model;
This will fix database update issue, but something wierd is still going on in the Connection.php file causing the error.
$statement = $this->getPdo()->prepare($query);
I am trying to learn more about Laravel ORM and ORM in general,
but I have problems I can't solve by myself.
This is my users table:
And here is my Article table:
My User eloquent model:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'users';
public function article()
{
return $this->hasMany('\App\Models\Article', 'autor_id');
}
}
And my Article eloquent model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'clanky';
public function autor() {
return $this->belongsTo('\App\Models\User', 'id');
}
}
I am trying to access each article with its author data using this code:
$articles = Models\Article::all();
foreach($articles as $art)
{
echo $art->autor->name . "<br>";
}
The problem is the model is returning only userdata from first article, not the second and so on.
Any thoughts on what could cause this? Thanks in advance.
I think you need to update your code like.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'Article';
public function autor() {
return $this->belongsTo('\App\Models\User', 'autor_id', 'id');
}
}
$articles = Models\Article::with('autor')->get();
foreach($articles as $art)
{
echo $art->autor->name . "<br>";
}
I am trying to chain 3 models together parent->child->child of child. So I can access it in an eloquent statement.
Parent Model:
class CertificationType extends Model
{
use SoftDeletes;
public $timestamps = true;
protected $table = 'certification_type';
protected $dates = ['deleted_at'];
protected $fillable = array('certification_type_name', 'fa_code', 'icon_image');
protected $hidden = ['created_at', 'updated_at',];
public function certification_type()
{
return $this->hasMany('App\Certification');
}
}
Child Model
class Certification extends Model
{
protected $table = 'certification';
public $timestamps = true;
use SoftDeletes;
protected $dates = ['deleted_at'];
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = array('certification_type_id', 'certification_name', 'certication_date', 'certification_license_number', 'certification_course_length', 'certification_course_description', 'certification_course_topics_list_id');
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'created_at', 'updated_at',
];
public function certification_type()
{
return $this->belongsTo('App\CertificationType',
'certification_type_id');
}
public function certification_course_topics_list()
{
return $this->hasMany('App\CertificationCourseTopicsList');
}
}
Child of Child Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class CertificationCourseTopicsList extends Model
{
protected $table = 'certification_topics_list';
public $timestamps = true;
use SoftDeletes;
protected $dates = ['deleted_at'];
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = array('certification_id', 'certification_topic_description');
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'created_at', 'updated_at',
];
public function certification_course_topics_list()
{
return $this->belongsToMany('App\Certification', 'certification_id');
}
}
The eloquent statement I am using is:
$CertificationTypes = App\CertificationType::orderBy('id',"asc")->with('certification_type')->get()->groupBy('id');
What I have accomplished is CertificationType has a child of Certifications attached in the query. What I need is the 2nd child to be in the query as well:
CertificationType::orderBy('id',"asc")->with('certification_type')->get()->groupBy('id')->with('certification')->get()->groupBy('id');
I also tried:
CertificationType::orderBy('id',"asc")->with('certification_type, certifications')->get()->groupBy('id');
That did not work: Call to undefined relationship [certification_type, certifications] on model [App\CertificationType].
Also tried:
CertificationType::orderBy('id',"asc")->with('certification_type', 'certifications')->get()->groupBy('id');
That did not work: Call to undefined relationship [certifications] on model [App\CertificationType].
Any help would be appreciated!
You need more order in code. I would make three models with proper relations as : belongsTo and hasMany. Then in each view you can use data from model with function of relation.
Example of proper model with relation:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
/**
* Get the comments for the blog post.
*/
public function comments()
{
return $this->hasMany('App\Comment');
}
}
Read more here, that will save your time: https://laravel.com/docs/5.5/eloquent-relationships#one-to-many
<?php
namespace App\Models;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Model implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['name', 'email', 'password'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password', 'remember_token'];
public static function boot()
{
parent::boot();
static::creating(function ($user) {
$user->activation_token = str_random(30);
});
}
public function gravatar($size = '100')
{
$hash = md5(strtolower(trim($this->attributes['email'])));
return "http://www.gravatar.com/avatar/$hash?s=$size";
}
public function statuses()
{
return $this->hasMany(Status::class);
}
public function feed()
{
return $this->statuses()->orderBy('created_at', 'desc');
}
public function followers()
{
return $this->belongsToMany(User::Class, 'followers', 'user_id', 'follower_id');
}
public function followings()
{
return $this->belongsToMany(User::Class, 'followers', 'follower_id', 'user_id');
}
public function follow($user_ids)
{
if (!is_array($user_ids)) {
$user_ids = compact('user_ids');
}
$this->followings()->sync($user_ids, false);
}
public function unfollow($user_ids)
{
if (!is_array($user_ids)) {
$user_ids = compact('user_ids');
}
$this->followings()->detach($user_ids);
}
public function isFollowing($user_id)
{
var_dump($this->followings);die();
return $this->followings->contains($user_id);
}
}
This is a code come from laravel models.
There is a method named $this->followings() .But I don't see any $this->followings attribute assigned in the code.
where is the $this->followings comes from?
thanks
Suggested reading about Laravel model relationships
in particular:
Once the relationship is defined, we may retrieve the related record using Eloquent's dynamic properties. Dynamic properties allow you to access relationship methods as if they were properties defined on the model
I have two models as Project and Collaborator this is My tables
Project column
id
project_name
project_note
user_id
Collaborator Model
id
project_id
collaborator_id
I need join this models to get project_name instead project_id of Collaborator Model.
how can I do this. I read www.laravel.com documents but difficult to understand. help me in code...
project Model
<?php
namespace App;
use Auth;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
/*
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['project_name', 'project_notes', 'project_status', 'due_date'];
public function scopePersonal($query)
{
return $query->where('user_id', Auth::user()->id);
}
//
}
collaborator Model
<?php
namespace App;
use Auth;
use Illuminate\Database\Eloquent\Model;
class Collaboration extends Model
{
protected $table = 'project_collaborator';
/*
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['project_id', 'collaborator_id'];
/*
* Get the user that is a collaborator on another project
* #return collection
*/
public function user()
{
return $this->belongsTo(User::class, 'collaborator_id');
}
/*
* Query scope to return information about the current project
* #param $query
* #param int $id
* #return query
*/
public function scopeProject($query, $id)
{
return $query->where('project_id', $id);
}
public function scopeColabo($query)
{
return $query->where('collaborator_id',Auth::user()->id);
}
}
Based on your comment, you need to add a relationship hasOne to your collaboration model:
class Collaboration extends Model
{
.....
public function project()
{
return $this->hasOne('App\Project');
}
.....
}
The method project() will define your relationship with your project model. And then you'll be able to get the collaboration project name like this:
$collaborations = Collaboration::with('project')->get();
foreach ( $collaborations as $collaboration ) {
echo $collaboration->project->project_name;
}
You can read more in the documentation.
In your Collaboration class add the followoing relation:
public function project()
{
return $this->belongsTo('App\Project');
}
And in your User class define a relation as:
public function collaborations()
{
return $this->hasMany('App\Collaboration', 'collaborator_id');
}
Then you can get all the collaborations of logged in user by:
$collaborations = auth()->user()->collaborations()->with('project')->get()
or
To get all collaborations you can so as:
$collaborations = Collaboration::with('project')->get();
In your view file:
#foreach ($collaborations as $collaboration)
{{ $collaboration->project->project_name }}
#endforeach