am trying to call functions inside my model in my controller but i get this error.
(1/1) ErrorException Non-static method App\User::getallreferrals() should not be called statically. in HomeController.php (line 37)
this is my model.
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Auth;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'first_name','last_name','other_name','user_name','number2','email', 'password', 'number','bank_name','acct_number','acct_name', 'next_kin', 'next_kin_no', 'transaction_details', 'entry_matrix','referral_id', 'referred_by','first_downline_id', 'second_downline_id'
];
/**
* The attributes that should be hidden for arrays. `1
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function scopeGetallreferrals($query)
{
return $query->where('referred_by', Auth::user()->referral_id)->pluck('referral_id');
}
public function scopeGetallreferralsobject($query)
{
return $query->where('referred_by', Auth::user()->referral_id)->get();
}
public function scopeGetallreferrals2genobject($query)
{
$referrals = $this->getallreferrals();
return $query->where('referred_by', $referrals)->get();
}
public function scopeGetallreferrals2gen($query)
{
$referrals = $this->getallreferrals();
return $query->where('referred_by', $referrals)->pluck('referral_id');
}
public function scopeGetallreferrals3gen($query){
$referrals2gen = $this->getallreferrals3gen();
return $query->where('referred_by', $referrals2gen)->pluck('referral_id');
}
public function scopeGetcaptain($query)
{
return $query->where('referral_id', Auth::user()->referred_by)->pluck('referred_by');
}
public function scopeGetallcaptain2gen($query)
{
$captain = $this->getcaptain();
return $query->where('referral_id', $captain)->pluck('referral_id');
}
public function scopeGetallcaptain3gen($query){
$captain2gen = $this->getcaptain2gen();
return $query->where('referred_by', $captain2gen)->pluck('referral_id');
}
public function scopeGetallreferralsbyID($query, $id){
return $this->getallreferrals()->where('id', $id);
}
public function scopeGetallreferrals2genbyID($query, $id){
return $this->getallreferrals2gen()->where('id', $id);
}
public function scopeGetallreferrals3genbyID($query, $id){
return $this->getallreferrals3gen()->where('id', $id);
}
}
then my controller.
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Http\Controllers\DateTime;
use App\User;
use Auth;
use Session;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$captain = User::getcaptain();
$referrals = User::getallreferrals();
return view('home', ['captain' => $captain, 'referrals' => $referrals]);
}
Please what am i not doing right? I have been on this project for a while now.
my migrations
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('first_name');
$table->string('last_name');
$table->string('other_name');
$table->string('user_name');
$table->string('number');
$table->string('number2');
$table->string('bank_name');
$table->string('acct_number');
$table->string('acct_name');
$table->string('email')->unique();
$table->string('password');
$table->string('next_kin');
$table->string('next_kin_no');
$table->string('entry_matrix');
$table->string('transaction_details')->nullable();
$table->integer('isconfirmed')->default(0);
$table->string('total_earned')->nullable();
$table->string('total_paid')->nullable();
$table->string('type_account')->nullable();
$table->integer('stage')->default(0);
$table->string('referral_id')->unique();
$table->string('referred_by')->nullable();
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
As it is saying the getallreferrals method is not static, but you are trying to call it with :, which means static.
It should be something like
use a Scope for this in User model
public function scopeGetallreferrals($query, $user)
{
return $query->where('referred_by', $user->referral_id);
}
and in controller
public function __construct(User $user)
{
$this->middleware('auth');
$this->user = Auth:user();
}
public function index()
{
$captain = $this->user->getcaptain();
$referrals = $this->user->getallreferrals($this->user)->pluck('referral_id');
return view('home', ['captain' => $captain, 'referrals' => $referrals]);
}
Related
i have a problem with function attach(). I have created 3 tables. 1 table is for added movies. Table 2 applies to the movie categories. 3 table is a collection of movie ID and category ID. A combination of many to many.
When i want add a new video with category from form this i have error -> Call to a member function attach() on boolean. If anyone knows the answer, please help. Thank you for your time!
VideoController.php -> look at the method store();
<?php
namespace App\Http\Controllers;
use Request;
use App\Http\Requests\CreateVideoRequest;
use App\Video;
use App\Category;
use Auth;
use Session;
class VideoController extends Controller
{
public function __construct(){
$this->middleware('auth', ['except' => 'index']);
}
public function index(){
$videos = Video::latest()->get();
return view('videos.index')->with('videos', $videos);
}
public function show($id){
$video = Video::find($id);
return view('videos.show')->with('video', $video);
}
public function create(){
$categories = Category::pluck('name', 'id');
return view('videos.create')->with('categories',$categories);
}
public function store(CreateVideoRequest $request){
$video = new Video($request->all());
//dd($request->all());
Auth::user()->videos()->save($video);
$categoryIds = $request->input('CategoryList');
$video->categories()->attach($categoryIds);
Session::flash('video_created', 'Added');
return redirect('video');
}
public function edit($id){
$video = Video::findOrFail($id);
return view('videos.edit')->with('video', $video);
}
public function update($id, CreateVideoRequest $request){
$video = Video::findOrFail($id);
$video->update($request->all());
return redirect('video');
}
}
Video.php - model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Video extends Model
{
protected $fillable = [
'title',
'url',
'description'
];
public function user(){
return $this->belongsTo('App\User');
}
public function categories(){
return $this->belongsToMany('App\Video')->withTimestamps;
}
}
Category.php - model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $fillable = [ 'name' ];
public function videos(){
return $this->belongsToMany('App/Video')->withTimestamps;
}
}
User.php - model (maybe you need a User.php model solves problems)
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* 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',
];
public function videos(){
return $this->hasMany('App\Video');
}
}
Migration - create_category_video_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCategoryVideoTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('category_video', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('category_id');
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
$table->unsignedBigInteger('video_id');
$table->foreign('video_id')->references('id')->on('videos')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('category_video');
}
}
Migration - create_categories_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCategoriesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('categories');
}
}
Migration - create_videos_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateVideosTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('videos', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->string('title');
$table->string('url');
$table->text('description');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('videos');
}
}
form.blade.php - simple form in Laravel Collection
{!! Form::select('CategoryList', $categories, null, ['multiple' => 'multiple']) !!}
For the timestamps for the pivot you would call the "method" withTimestamps() not a "property" named withTimestamps:
// Video
public function categories()
{
return $this->belongsToMany(Category::class)->withTimestamps();
}
// Category
public function videos()
{
return $this->belongsToMany(Video::class)->withTimestamps();
}
I just made a delete function of accounts, but I'm stuck on a problem.I need to also delete posts of user, at delete account.How can I make that? I have table Users, where I have all details from users, and table Posts, where also have user_id and id,caption and image of post.
public function delete($id)
public function delete($id)
{
$profile = User::find($id);
$profile->delete();
Session::flash('remove', "The profile was successfully deleted!");
return redirect('login');
}
Profile.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
protected $guarded = [];
public function profileImage(){
$imagePath = ($this->image) ? $this->image : 'profile/vx2k9TEhkcgaRdOWKvs4lsxqOVmuzwumtwySEnvH.png';
return '' . $imagePath;
}
public function user(){
return $this->belongsTo(User::class);
}
public function followers(){
return $this->belongsToMany(User::class);
}
}
User.php
<?php
namespace App;
use App\Mail\NewUserWelcomeMail;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Mail;
use Actuallymab\LaravelComment\CanComment;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'username', 'password',
];
/**
* 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',
];
protected static function boot()
{
parent::boot();
static::created(function ($user) {
$user->profile()->create([
'title' => $user->username,
]);
});
}
public function posts()
{
return $this->hasMany(Post::class)->orderBy('created_at', 'DESC');
}
public function profile()
{
return $this->hasOne(Profile::class);
}
}
Post.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $guarded = [];
public function user(){
return $this->belongsTo(User::class);
}
public function likes()
{
return $this->hasMany('App\Like');
}
public function comments()
{
return $this->hasMany('App\Comment');
}
public function tags()
{
return $this->belongsToMany('App\Tag');
}
}
Migration posts table
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->string('caption');
$table->string('image');
$table->timestamps();
$table->index('user_id');
});
}
I think you could try to delete related model in the controller before the user, i.e.:
public function delete($id)
{
$profile = User::find($id);
$profile->posts()->delete();
$profile->delete();
Session::flash('remove', "The profile was successfully deleted!");
return redirect('login');
}
Or you can go with model event, i.e.:
protected static function boot() {
parent::boot();
static::created(function ($user) {
$user->profile()->create([
'title' => $user->username,
]);
});
static::deleting(function($user) {
$user->posts()->delete();
});
}
I am struggling to see, where I went wrong. It seams easy, I followed Laravel instructions https://laravel.com/docs/5.4/eloquent-relationships#has-many-through , but clearly I need someone more familar with this sort of code as whenever I try to fetch $stagingsystem-stagesubtype I get error
BadMethodCallException with message 'Call to undefined method >Illuminate\Database\Query\Builder::hasManyTrough()'
Can someone help?
StagingSystems
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateStagingSystemsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('staging_systems', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('staging_systems');
}
}
StageName
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateStageNamesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('stage_names', function (Blueprint $table) {
$table->increments('id');
$table->integer('staging_system_id')->unsigned();
$table->foreign('staging_system_id')->references('id')->on('staging_systems');
$table->string('name')->unique;
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('stage_names');
}
}
StageSubType
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateStageSubTypesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('stage_sub_types', function (Blueprint $table) {
$table->increments('id');
$table->integer('stage_name_id')->unsigned();
$table->foreign('stage_name_id')->references('id')->on('stage_names');
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('stage_sub_types');
}
}
MODELS
StagingSystem
<?php
namespace App;
use App\StagingSystem;
use Illuminate\Database\Eloquent\Model;
class StagingSystem extends Model
{
protected $guarded = ['id'];
public function stagename()
{
return $this->hasMany('App\StageName');
}
public function stagesubtype()
{
return $this->hasManyTrough('App\StageSubType','App\StageName');
}
}
StageName
<?php
namespace App;
use App\StageName;
use Illuminate\Database\Eloquent\Model;
class StageName extends Model
{
protected $guarded = ['id'];
public function stagingsystem()
{
return $this->belongsTo('App\StagingSystem','id');
}
public function stagesubtype()
{
return $this->hasMany('App\StageSubType');
}
}
StageSubType
<?php
namespace App;
use App\StageSubType;
use Illuminate\Database\Eloquent\Model;
class StageSubType extends Model
{
protected $guarded = [
'id'
];
public function stagename()
{
return $this->belongsTo('App\StageName');
}
public function stagingsystem()
{
return $this->belongsTo('App\StagingSystem');
}
}
For anyone coming across this with a similar issue, this error message can appear if you are trying to access a models relationship using withPivot(), but the intermediate relationship extends Model instead of Pivot.
You have mistyped HasManyThrough as hasManyTrough.
I have been in big problem, I am maintaining eloquent relationship setup in my project where i am having the following relationship:
User info related to login stored in users table.
User profile related information stored in profiles information.
Users address stored in address table
configurations related information stored in configurations like city, state, country
Efforts
Here is the migration and model and their relationship:
Users migration table:
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('users');
}
}
User Model:
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'email', 'password',
];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function profile()
{
return $this->hasOne('App\Profile','user_id');
}
}
Profile migration table:
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProfilesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('profiles', function (Blueprint $table) {
$table->increments('profile_id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->string('lastname')->nullable();
$table->string('firstname')->nullable();
$table->string('gender')->nullable();
$table->string('phonenumber', 20)->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('profiles');
}
}
Profile Model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
protected $fillable = [
'firstname', 'lastname',
];
public function user(){
return $this->belongsTo('App\User');
}
public function address()
{
return $this->hasOne('App\Address','profile_id');
}
}
Configuration migration table:
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateConfigurationsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('configurations', function (Blueprint $table) {
$table->increments('config_id');
$table->string('configuration_name');
$table->string('configuration_type');
$table->string('parent_id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('configurations');
}
}
Configuration Model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Configuration extends Model
{
public function children() {
return $this->hasMany('App\Configuration','parent_id');
}
public function parent() {
return $this->belongsTo('App\Configuration','parent_id');
}
public function city() {
return $this->hasOne('App\Address', 'city');
}
public function state() {
return $this->hasOne('App\Address', 'state');
}
public function country() {
return $this->hasOne('App\Address', 'country');
}
}
Address Migration Table:
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateAddressesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('addresses', function (Blueprint $table) {
$table->increments('address_id');
$table->integer('profile_id')->unsigned();
$table->foreign('profile_id')->references('profile_id')->on('profiles')->onDelete('cascade');
$table->string('address')->nullable();
$table->integer('city')->unsigned();
$table->foreign('city')->references('config_id')->on('configurations')->onDelete('cascade');
$table->string('pincode')->nullable();
$table->integer('state')->unsigned();
$table->foreign('state')->references('config_id')->on('configurations')->onDelete('cascade');
$table->integer('country')->unsigned();
$table->foreign('country')->references('config_id')->on('configurations')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('addresses');
}
}
Address Model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Address extends Model
{
public function profile(){
return $this->belongsTo('App\Profile');
}
public function city() {
return $this->belongsTo('App\Configuration');
}
public function state() {
return $this->belongsTo('App\Configuration');
}
public function country() {
return $this->belongsTo('App\Configuration');
}
}
I have used Eloquent relation setup, two foreign keys to same table to make my project relationship. But unfortunately above code does not generating desire output. Take a look:
If I use the command Auth::user()->profile->firstname it will print user first name. So if i use Auth::user()->profile->address->city it should print city name stored in configuration table, but instead print name it print the id.
Please suggest me the solution.
Thanks,
Well, I found the solution for my own question. Thanks for everyone who think this question have some worth.
Well, we don't nedd to change user or profile, we just need to make some changes in configuration and address model only.
change
class Address extends Model
{
public function profile(){
return $this->belongsTo('App\Profile');
}
public function city() {
return $this->belongsTo('App\Configuration');
}
public function state() {
return $this->belongsTo('App\Configuration');
}
public function country() {
return $this->belongsTo('App\Configuration');
}
}
to
class Address extends Model
{
public function profile(){
return $this->belongsTo('App\Profile');
}
public function cityConfiguration() {
return $this->belongsTo('App\Configuration', 'city');
}
public function stateConfiguration() {
return $this->belongsTo('App\Configuration', 'state');
}
public function countryConfiguration() {
return $this->belongsTo('App\Configuration', 'country');
}
}
and change
class Configuration extends Model
{
public function children() {
return $this->hasMany('App\Configuration','parent_id');
}
public function parent() {
return $this->belongsTo('App\Configuration','parent_id');
}
public function city() {
return $this->hasOne('App\Address', 'city');
}
public function state() {
return $this->hasOne('App\Address', 'state');
}
public function country() {
return $this->hasOne('App\Address', 'country');
}
}
To
class Configuration extends Model
{
public function children() {
return $this->hasMany('App\Configuration','parent_id');
}
public function parent() {
return $this->belongsTo('App\Configuration','parent_id');
}
public function city() {
return $this->hasOne('App\Address', 'city');
}
public function state() {
return $this->hasOne('App\Address', 'state');
}
public function country() {
return $this->hasOne('App\Address', 'country');
}
}
and that's it. Everything is working fine.
my problem is, that my hasMany relationship returns just an "empty" collection:
Collection {#172 ▼
#items: array:1 [▼
0 => 0
]
}
My belongsTo relationship just returns "null".
Here are the eloquents:
Game.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
/**
* App\Models\Game
*
* #property integer $id
* #property integer $steamid
* #property string $name
* #property \Carbon\Carbon $created_at
* #property \Carbon\Carbon $updated_at
*/
class Game extends Model
{
protected $fillable = [
'appid', 'name'
];
public function keys()
{
$this->hasMany('App\Models\Game\Key', 'id', 'game_id');
}
}
Key.php
<?php
namespace App\Models\Game;
use Illuminate\Database\Eloquent\Model;
/**
* App\Models\Game\Key
*
*/
class Key extends Model
{
protected $fillable = [
'key', 'game_id', 'author_id',
];
public static function getRandom()
{
if (!self::available()) return false;
$keys = Key::where('redeemer_id', 0)->get();
$key = $keys[ rand(0, count($keys) - 1) ];
return $key;
}
public static function available()
{
$keys = Key::where('redeemer_id', 0)->get();
$count = count($keys);
if ($count > 0) return $count;
return false;
}
public function author()
{
$this->hasOne('App\Models\User', 'author_id');
}
public function redeemer()
{
$this->hasOne('App\Models\User', 'redeemer_id');
}
public function game()
{
$this->belongsTo('App\Models\Game', 'game_id');
}
}
User.php
<?php
namespace App\Models;
use Carbon\Carbon;
use Illuminate\Foundation\Auth\User as Authenticatable;
/**
* App\Models\User
*
* #property integer $id
* #property string $name
* #property string $email
* #property string $password
* #property string $remember_token
* #property \Carbon\Carbon $created_at
* #property \Carbon\Carbon $updated_at
*/
class User extends Authenticatable
{
protected $fillable = [
'username', 'email', 'password'
];
protected $hidden = [
'password', 'remember_token',
];
public function keys()
{
$this->hasMany('App\Models\Game\Key');
}
public function canRedeem()
{
// TODO: not tested yet
if(count(self::keys()) == 0) return true;
if(Carbon::now(-24) > self::keys()->first()->created_at) return true;
return false;
}
}
these are my migrations:
user-table
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('username')->unique();
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('users');
}
}
game-table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateGamesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
if (!Schema::hasTable('games')) {
Schema::create('games', function (Blueprint $table) {
$table->increments('id');
$table->integer('appid')->unsigned();
$table->string('name');
$table->timestamps();
});
}
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
//Schema::drop('games');
}
}
keys-table
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateKeysTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('keys', function(Blueprint $table) {
$table->increments('id');
$table->string('key');
$table->integer('game_id')->unsigned()->index();
$table->foreign('game_id')->references('id')->on('games')->onDelete('cascade');
$table->integer('author_id')->unsigned()->index();
$table->integer('redeemer_id')->unsigned()->index();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('keys');
}
}
I googled alot and I found some "solutions" on Laracast, but they only tell me what I already have.
Can anyone help?
Deazl
The method that creates the relationship has to return a value, this is what I am saying:
Rather than:
public function keys()
{
$this->hasMany('App\Models\Game\Key', 'id', 'game_id');
}
You should have:
public function keys()
{
return $this->hasMany('App\Models\Game\Key', 'id', 'game_id');
}
The difference is the return statement, your methods that create the relationship do not return any, they should return the results of the hasOne and hasMany for all method that uses them for query building.
PS: You should add the return statement for the other methods that create a relationship.
If you have extra columns in your intermediate table you need to include them when defining your relation.
public function keys()
{
$this->hasMany('App\Models\Game\Key')->withPivot('author_id','redeemer_id')->withTimestamps();
}