Laravel - How to get user id in app service provider - laravel

I try to get user id in my app service provider, but I get an error show that ErrorException: Trying to get property of non-object, any idea how on how to get user id?
AppServiceProvider:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Project;
use Log;
use Auth;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
$userid = Auth::user()->id;
Log::info('userid :', [$userid]);
$project = Project::where('user_id',Auth::user()->id)->count();
}
}
Error:
local.ERROR: ErrorException: Trying to get property of non-object in C:\wamp64\www\test\app\Providers\AppServiceProvider.php:20 Stack trace: #0 C:\wamp64\www\test\app\Providers\AppServiceProvider.php(20): Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(8, 'Trying to get p...', 'C:\\wamp64\\www\\f...', 20, Array) #1 [internal function]: App\Providers\AppServiceProvider->boot() #2 C:\wamp64\www\test\vendor\laravel\framework\src\Illuminate\Container\Container.php(507): call_user_func_array(Array, Array) #3 C:\wamp64\www\test\vendor\laravel\framework\src\Illuminate\Foundation\Application.php(734): Illuminate\Container\Container->call(Array) #4 C:\wamp64\www\test\vendor\laravel\framework\src\Illuminate\Foundation\Application.php(717): Illuminate\Foundation\Application->bootProvider(Object(App\Providers\AppServiceProvider)) #5 [internal function]: Illuminate\Foundation\Application->Illuminate\Foundation\{closure}(Object(App\Providers\AppServiceProvider), 19) #6 C:\wamp64\www\test\vendor\laravel\framework\src\Illuminate\Foundation\Application.php(718): array_walk(Array, Object(Closure)) #7 C:\wamp64\www\test\vendor\laravel\framework\src\Illuminate\Foundation\Bootstrap\BootProviders.php(17): Illuminate\Foundation\Application->boot() #8 C:\wamp64\www\test\vendor\laravel\framework\src\Illuminate\Foundation\Application.php(203): Illuminate\Foundation\Bootstrap\BootProviders->bootstrap(Object(Illuminate\Foundation\Application)) #9 C:\wamp64\www\test\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(222): Illuminate\Foundation\Application->bootstrapWith(Array) #10 C:\wamp64\www\test\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(117): Illuminate\Foundation\Http\Kernel->bootstrap() #11 C:\wamp64\www\test\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(87): Illuminate\Foundation\Http\Kernel->sendRequestThroughRouter(Object(Illuminate\Http\Request)) #12 C:\wamp64

Use View::composer('*',) to use Auth in all view .
use Illuminate\Support\Facades\View;
.........
public function boot()
{
View::composer('*', function($view)
{
if (Auth::check()){
$project = Project::where('user_id',Auth::id() )->count();
}
});
You can understand it as after authentication before view render you need to check between these not before.

Auth will always try to get the id even user is logged in or not. In case user is not logged in then it will give you non-object error because nothing is there to get via User model object.
public function boot()
{
if (Auth::check()) {
$userid = Auth::user()->id;
Log::info('userid :', [$userid]);
$project = Project::where('user_id',Auth::user()->id)->count();
}
}
Good luck.

In the boot() method of your service providers, you should only bootstrap your application and not perform any action regarding looking up or outputting data. You can do this in the register() method of your providers, if it is really necessary to do it in a service provider. A better place would probably be a controller or a command anyway, though.
Using Auth::user() directly is dangerous as well, because there might be no user authenticated in your app. You can instead perform a if(Auth::check()) { ... } before accessing the user with Auth::user(), or, which in your case would be sufficient, you can access the user id with Auth::id(). It will also return null if no user is available, i.e. Auth::check() === false.

Related

How to set Null to the related table record on soft delete in Laravel5

I'm new to Laravel.
I have two tables related to each other.
I want to set null to the related table record when the other related table record is soft deleted.
I know how to soft delete when the other related table record, but how can I set null instead of soft-delete?
Product Model (Edited)
class Product extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
public $table = "products";
public function projects()
{
return $this->hasMany("App\Model\Project");
}
public static function boot(){
parent::boot();
static::deleted(function($product)
{
//set null
$product->projects()->setNull();
});
}
}
Project Model(Edited)
<?php
class Project extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
public function product()
{
return $this->belongsTo("App\Model\Product");
}
public function setNull()
{
$this->product_id = NULL;
$this->save();
}
}
Table Schema
Schema::create('projects', function (Blueprint $table) {
$table->increments('id');
$table->string('project_name')->unique("project_name");
$table->integer('project_value')->unsigned();
$table->integer('product_id')->unsigned()->nullable();
$table->foreign('product_id')->references('id')->on('products')->onDelete("set null");
$table->timestamps();
$table->softDeletes();
$table->engine = 'InnoDB';
});
note
one project belongs to one product. It seems a bit weird but it's ok.
Error Message
When I delete a product record, I got the following error.
[2017-05-13 17:25:28] local.ERROR: BadMethodCallException: Call to undefined method Illuminate\Database\Query\Builder::setNull() in /vagrant/door/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php:2443
Stack trace:
#0 /vagrant/door/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php(1239): Illuminate\Database\Query\Builder->__call('setNull', Array)
#1 [internal function]: Illuminate\Database\Eloquent\Builder->__call('setNull', Array)
#2 /vagrant/door/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Relation.php(340): call_user_func_array(Array, Array)
#3 /vagrant/door/app/Model/Product.php(44): Illuminate\Database\Eloquent\Relations\Relation->__call('setNull', Array)
#4 /vagrant/door/vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php(348): App\Model\Product::App\Model\{closure}(Object(App\Model\Product))
#5 /vagrant/door/vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php(199): Illuminate\Events\Dispatcher->Illuminate\Events\{closure}('eloquent.delete...', Array)
#6 /vagrant/door/vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php(172): Illuminate\Events\Dispatcher->dispatch('eloquent.delete...', Array, false)
#7 /vagrant/door/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasEvents.php(148): Illuminate\Events\Dispatcher->fire('eloquent.delete...', Object(App\Model\Product))
#8 /vagrant/door/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(748): Illuminate\Database\Eloquent\Model->fireModelEvent('deleted', false)
#9 /vagrant/door/app/Http/Controllers/ProductController.php(80): Illuminate\Database\Eloquent\Model->delete()
#10 [internal function]: App\Http\Controllers\ProductController->destroy(Object(App\Http\Requests\ProductRequest), '1')
Check out dissociate() method, this will reset both the foreign key of the relation and the relation on the object.
Basically you want something like this:
static::deleted(function($product)
{
// remove relation
$product->projects()->each(function($project) {
$project->product()->dissociate();
$project->save();
});
});
In your project model define a custom method like,
public function setNull()
{
$this->field_names= NULL;
$this->save();
}
Then in the boot function you call this method like
$product->projects()->setNull();
P. S- sorry I'm on mobile

Class not found exception in job (queue)

We want to use laravel jobs for sending out invoices to customers.
We have this job class. It expects the payment model in the constructor.
namespace App\Jobs;
use App\Jobs\Job;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class SendInvoiceEmail extends Job implements ShouldQueue
{
use InteractsWithQueue, SerializesModels;
public $paypalModel;
/**
* Create a new job instance.
*
* #return void
*/
public function __construct($paypalModel)
{
$this->paypalModel = $paypalModel;
}
/**
* The number of times the job may be attempted.
*
* #var int
*/
public $tries = 5;
/**
* Execute the job.
*
* #return void
*/
public function handle()
{
$rechnung = new \App\Classes\Rechnung\Rechnung($this->paypalModel);
$rechnung->platzhalterErsetzen();
$rechnung->pdfErzeugen();
\App\Classes\Mail::SendPHPMail([
'email'=> $this->paypalModel->benutzer->email,
'name' => $this->paypalModel->benutzer->vorname . ' ' .$this->paypalModel->benutzer->nachname,
'type' => 'SendInvoice',
'invoicePath'=> $rechnung->pdfTargetPath
]);
$this->paypalModel->rechnungGesendet = true;
$this->paypalModel->save();
}
}
If we set the queue_driver in the env to sync it works perfectly. Now if we change the queue_driver to database and start a listener on the jobs, we always get this exception:
[2017-03-15 13:20:13] local.ERROR: Symfony\Component\Debug\Exception\FatalThrowableError: Class 'app\Models\Payment\PayPal\PayPal' not found in d:\project\vendor\laravel\framework\src\Illuminate\Queue\SerializesModels.php:76 Stack trace:
#0 d:\project\vendor\laravel\framework\src\Illuminate\Queue\SerializesModels.php(42): App\Jobs\SendInvoiceEmail->getRestoredPropertyValue(Object(Illuminate\Contracts\Database\ModelIdentifier))
#1 [internal function]: App\Jobs\SendInvoiceEmail->__wakeup()
#2 d:\project\vendor\laravel\framework\src\Illuminate\Queue\CallQueuedHandler.php(38): unserialize('O:25:"App\\Jobs\\...')
#3 d:\project\vendor\laravel\framework\src\Illuminate\Queue\Jobs\Job.php(130): Illuminate\Queue\CallQueuedHandler->call(Object(Illuminate\Queue\Jobs\DatabaseJob), Array)
#4 d:\project\vendor\laravel\framework\src\Illuminate\Queue\Jobs\DatabaseJob.php(49): Illuminate\Queue\Jobs\Job->resolveAndFire(Array)
#5 d:\project\vendor\laravel\framework\src\Illuminate\Queue\Worker.php(213): Illuminate\Queue\Jobs\DatabaseJob->fire()
#6 d:\project\vendor\laravel\framework\src\Illuminate\Queue\Worker.php(156): Illuminate\Queue\Worker->process('database', Object(Illuminate\Queue\Jobs\DatabaseJob), '0', '0')
#7 d:\project\vendor\laravel\framework\src\Illuminate\Queue\Console\WorkCommand.php(125): Illuminate\Queue\Worker->pop(NULL, 'rechnung', '0', '3', '0')
#8 d:\project\vendor\laravel\framework\src\Illuminate\Queue\Console\WorkCommand.php(78): Illuminate\Queue\Console\WorkCommand->runWorker(NULL, 'rechnung', '0', '128', false)
#9 [internal function]: Illuminate\Queue\Console\WorkCommand->fire()
#10 d:\project\vendor\laravel\framework\src\Illuminate\Container\Container.php(507): call_user_func_array(Array, Array)
#11 d:\project\vendor\laravel\framework\src\Illuminate\Console\Command.php(169): Illuminate\Container\Container->call(Array)
#12 d:\project\vendor\symfony\console\Command\Command.php(267): Illuminate\Console\Command->execute(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#13 d:\project\vendor\laravel\framework\src\Illuminate\Console\Command.php(155): Symfony\Component\Console\Command\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#14 d:\project\vendor\symfony\console\Application.php(846): Illuminate\Console\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#15 d:\project\vendor\symfony\console\Application.php(191): Symfony\Component\Console\Application->doRunCommand(Object(Illuminate\Queue\Console\WorkCommand), Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#16 d:\project\vendor\symfony\console\Application.php(122): Symfony\Component\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#17 d:\project\vendor\laravel\framework\src\Illuminate\Foundation\Console\Kernel.php(107): Symfony\Component\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#18 d:\project\artisan(35): Illuminate\Foundation\Console\Kernel->handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#19 {main}
Why does the listener not know the class and when running in sync mode, it works as expected? Does anybody have a hint, what the reason can be and where to search for the error reason?
Thanks in advance!
UPDATE
I've added as proposed from #niraj-shah the class app\Models\Payment\PayPal\PayPal:
...
namespace App\Jobs;
use App\Jobs\Job;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use app\Models\Payment\PayPal\PayPal;
class SendInvoiceEmail extends Job implements ShouldQueue
{
...
This did not solve the problem. Still the same error message appears. Even when I delete old created jobs and did a queue:restart to load the new code. Any other hint?
Your code cannot find the PayPal class. Please add a use statement to the top of your code (after the other use statements)` pointing to the location of the PayPal class. E.g.
use App\Jobs\Job;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Models\Payment\PayPal\PayPal;
....

Laravel 5.2.14 with Duxet/RethinkDB Seeding Error

I've setup a per project install of Homestead for this project so I don't add RethinkDB to all my Laravel applications. I've been able very easily setup RethinkDB in Homestead, and migrate the database tables, but I can't seem to seed them. Running php artisan db:seed throws this error in the terminal:
[Symfony\Component\Debug\Exception\FatalThrowableError]
Fatal error: Call to a member function prepare() on null
And this error in laravel.log:
[2016-02-11 02:15:39] local.ERROR: Symfony\Component\Debug\Exception\FatalThrowableError: Fatal error: Call to a member function prepare() on null in /home/vagrant/app/vendor/laravel/framework/src/Illuminate/Database/Connection.php:390
Stack trace:
#0 /home/vagrant/app/vendor/laravel/framework/src/Illuminate/Database/Connection.php(644): Illuminate\Database\Connection->Illuminate\Database\{closure}(Object(duxet\Rethinkdb\Connection), 'insert into "us...', Array)
#1 /home/vagrant/app/vendor/laravel/framework/src/Illuminate/Database/Connection.php(611): Illuminate\Database\Connection->runQueryCallback('insert into "us...', Array, Object(Closure))
#2 /home/vagrant/app/vendor/laravel/framework/src/Illuminate/Database/Connection.php(391): Illuminate\Database\Connection->run('insert into "us...', Array, Object(Closure))
#3 /home/vagrant/app/vendor/laravel/framework/src/Illuminate/Database/Connection.php(347): Illuminate\Database\Connection->statement('insert into "us...', Array)
#4 /home/vagrant/app/vendor/laravel/framework/src/Illuminate/Database/Query/Processors/Processor.php(32): Illuminate\Database\Connection->insert('insert into "us...', Array)
#5 /home/vagrant/app/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php(1889): Illuminate\Database\Query\Processors\Processor->processInsertGetId(Object(Illuminate\Database\Query\Builder), 'insert into "us...', Array, 'id')
#6 [internal function]: Illuminate\Database\Query\Builder->insertGetId(Array, 'id')
#7 /home/vagrant/app/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php(1244): call_user_func_array(Array, Array)
#8 /home/vagrant/app/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(1683): Illuminate\Database\Eloquent\Builder->__call('insertGetId', Array)
#9 /home/vagrant/app/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(1652): Illuminate\Database\Eloquent\Model->insertAndSetId(Object(Illuminate\Database\Eloquent\Builder), Array)
#10 /home/vagrant/app/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(1543): Illuminate\Database\Eloquent\Model->performInsert(Object(Illuminate\Database\Eloquent\Builder), Array)
#11 /home/vagrant/app/vendor/laravel/framework/src/Illuminate/Database/Eloquent/FactoryBuilder.php(86): Illuminate\Database\Eloquent\Model->save()
#12 /home/vagrant/app/database/seeds/UserTableSeeder.php(35): Illuminate\Database\Eloquent\FactoryBuilder->create()
#13 /home/vagrant/app/vendor/laravel/framework/src/Illuminate/Database/Seeder.php(39): UserTableSeeder->run()
#14 /home/vagrant/app/database/seeds/DatabaseSeeder.php(27): Illuminate\Database\Seeder->call('UserTableSeeder')
#15 /home/vagrant/app/vendor/laravel/framework/src/Illuminate/Database/Console/Seeds/SeedCommand.php(63): DatabaseSeeder->run()
#16 /home/vagrant/app/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(2347): Illuminate\Database\Console\Seeds\SeedCommand->Illuminate\Database\Console\Seeds\{closure}()
#17 /home/vagrant/app/vendor/laravel/framework/src/Illuminate/Database/Console/Seeds/SeedCommand.php(64): Illuminate\Database\Eloquent\Model::unguarded(Object(Closure))
#18 [internal function]: Illuminate\Database\Console\Seeds\SeedCommand->fire()
#19 /home/vagrant/app/vendor/laravel/framework/src/Illuminate/Container/Container.php(507): call_user_func_array(Array, Array)
#20 /home/vagrant/app/vendor/laravel/framework/src/Illuminate/Console/Command.php(169): Illuminate\Container\Container->call(Array)
#21 /home/vagrant/app/vendor/symfony/console/Command/Command.php(256): Illuminate\Console\Command->execute(Object(Symfony\Component\Console\Input\ArrayInput), Object(Illuminate\Console\OutputStyle))
#22 /home/vagrant/app/vendor/laravel/framework/src/Illuminate/Console/Command.php(155): Symfony\Component\Console\Command\Command->run(Object(Symfony\Component\Console\Input\ArrayInput), Object(Illuminate\Console\OutputStyle))
#23 /home/vagrant/app/vendor/laravel/framework/src/Illuminate/Console/Command.php(185): Illuminate\Console\Command->run(Object(Symfony\Component\Console\Input\ArrayInput), Object(Illuminate\Console\OutputStyle))
#24 /home/vagrant/app/vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/MigrateCommand.php(90): Illuminate\Console\Command->call('db:seed', Array)
#25 [internal function]: Illuminate\Database\Console\Migrations\MigrateCommand->fire()
#26 /home/vagrant/app/vendor/laravel/framework/src/Illuminate/Container/Container.php(507): call_user_func_array(Array, Array)
#27 /home/vagrant/app/vendor/laravel/framework/src/Illuminate/Console/Command.php(169): Illuminate\Container\Container->call(Array)
#28 /home/vagrant/app/vendor/symfony/console/Command/Command.php(256): Illuminate\Console\Command->execute(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#29 /home/vagrant/app/vendor/laravel/framework/src/Illuminate/Console/Command.php(155): Symfony\Component\Console\Command\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#30 /home/vagrant/app/vendor/symfony/console/Application.php(791): Illuminate\Console\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#31 /home/vagrant/app/vendor/symfony/console/Application.php(186): Symfony\Component\Console\Application->doRunCommand(Object(Illuminate\Database\Console\Migrations\MigrateCommand), Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#32 /home/vagrant/app/vendor/symfony/console/Application.php(117): Symfony\Component\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#33 /home/vagrant/app/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(107): Symfony\Component\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#34 /home/vagrant/app/artisan(35): Illuminate\Foundation\Console\Kernel->handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
My Seed for Users is pretty typical:
<?php
use Illuminate\Database\Seeder;
class UserTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
// Developer accounts
factory(App\User::class, 'admin', 1)->create([
'username' => 'test',
'email' => 'test#domain.com'
]);
factory(App\User::class, 1)->create();
}
}
With a simple model factory:
<?php
/**
* Define a general user factory for seeding the database.
*/
$factory->define(App\User::class, function (Faker\Generator $faker) {
return [
'username' => $faker->name,
'password' => bcrypt(str_random(10)),
'email' => $faker->email,
'remember_token' => str_random(10),
];
});
/**
* Define an administrator factory for seeding the database.
*/
$factory->defineAs(App\User::class, 'admin', function (Faker\Generator $faker) use ($factory) {
// Reuse general user factory attributes
$user = $factory->raw(App\User::class);
return array_merge($user, [
'role' => 'admin'
]);
});
Update
It appears it might be an issue between RethinkDB and Laravel, but I'm not sure how to go about fixing it. This is the method that the issue occurs in, where I logged out to Laravel.log using monolog, and included the output below the log statements. It appears the method getPdo() is null.
public function statement($query, $bindings = [])
{
return $this->run($query, $bindings, function ($me, $query, $bindings) {
if ($me->pretending()) {
return true;
}
Log::info($query);
// insert into "users" ("username", "password", "email", "remember_token", "role", "updated_at", "created_at") values (?, ?, ?, ?, ?, ?, ?)
$bindings = $me->prepareBindings($bindings);
Log::info($bindings);
// array (
// 0 => 'test',
// 1 => '$2y$10$8icEztzBbFL/556imvn8D.905i67RrCuUwf6csaN2r75W0s0ifg/a',
// 2 => 'test#domain.com',
// 3 => 'WUA1vvpyvQ',
// 4 => 'admin',
// 5 => '2016-02-11 03:33:29',
// 6 => '2016-02-11 03:33:29',
// )
Log::info($me->getPdo());
// null
return $me->getPdo()->prepare($query)->execute($bindings);
});
}
It looks like this failed due to the User model being the only model that wasn't generate through artisan using make:rethink-model, and it pulls in Authenticatable, which uses the Illuminate Model class. To fix this it has to be updated manually by removing use Illuminate\Foundation\Auth\User as Authenticatable; and then applying the traits it contains directly to the User model, but then inherits from use \duxet\Rethinkdb\Eloquent\Model; so your final User class at the bare minimum will now look like this:
namespace App;
use Illuminate\Auth\Authenticatable;
use \duxet\Rethinkdb\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 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',
];
}

Using Eloquent in Codeigniter, I'm having trouble setting up relationships

I followed this tutorial to get Laravel's Eloquent running inside an existing Codeigniter project and everything worked fine until I attemped to use Eloquent's relationships. Here's my offending code:
class Announcement_model extends Eloquent {
protected $table = 'announcements';
public function game() {
$this->load->model('game_model');
return $this->belongsTo('Game_model', 'game_id');
}
}
class Game_model extends Eloquent {
protected $table = 'games';
}
And the controller:
class Api_announcement extends REST_Controller {
...
public function index_get() {
$response = Announcement_model::with('game')->get();
$this->response(array('error'=> false, 'response' => $response), 200);
}
}
I'm running into this error:
<b>Fatal error</b>: Uncaught exception 'LogicException' with message 'Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation' in myproject\vendor\illuminate\database\Eloquent\Model.php:2695
Stack trace:
#0 myproject\vendor\illuminate\database\Eloquent\Model.php(2665): Illuminate\Database\Eloquent\Model->getRelationshipFromMethod('load')
#1 myproject\vendor\illuminate\database\Eloquent\Model.php(2607): Illuminate\Database\Eloquent\Model->getRelationValue('load')
#2 myproject\vendor\illuminate\database\Eloquent\Model.php(3325): Illuminate\Database\Eloquent\Model->getAttribute('load')
#3 myproject\application\models\announcement_model.php(11): Illuminate\Database\Eloquent\Model->__get('load')
#4 myproject\vendor\illuminate\database\Eloquent\Builder.php(477): Announcement_model->game()
#5 [internal function]: Illuminate\Database\Eloquent\Builder->Illuminate\Database\Eloquent\{closure}()
#6 in
<b>myproject\vendor\illuminate\database\Eloquent\Model.php</b> on line
<b>2695</b>
What am I doing wrong? I've looked up and down for a solution but nothing works.
return $this->belongsTo('Game_model', 'game_id')->select(array('name'));
Returns in array, but no Relation. You need this:
return $this->belongsTo('Game_model', 'game_id');

Laravel 4 white screen using eloquent

I'm trying to pass an array of database entries to a view using Eloquent. I'm new to MVC development. The code is as follows:
School.php (model)
class School extends Eloquent
{
protected $table = 'Schools';
public $timestamps = false;
protected $softDelete = false;
public function school()
{
return $this->hasOne('School');
}
}
SchoolController.php (controller)
class SchoolController extends BaseController
{
public $restful = true;
public function getIndex()
{
return View::make('schools')
->with('schools', School::all());
}
}
schools.blade.php (View)
#extends('layouts.schools')
#section('school-search')
<ul>
#foreach($schools as $school)
<li>{{ $school->name }}</li>
#endforeach
</ul>
#stop
However, I'm getting a white screen of death when I load the page. The view works fine when I comment out the "->with('schools', School::all())" part, so I think it has to do with Laravel failing to access the School object. I've googled/stackoverflowed a bit and can't find anyone with a similar problem.
Thanks!
edit: Some relevant info:
I have had this problem before, where it would whitescreen anything I routed to, however I corrected that by changing app/storage permissions. Changing permissions does not seem to help this whitescreen problem.
Laravel seems to be error reporting just fine. When there is something that doesn't make sense in my code, I get an error.
We are in development environment.
edit:
when I run php artisan serve, it gives an error "This php binary is not version 5.4 or greater" Could this be related?
edit:
I've updated to PHP 5.4. Still whitescreening. Here is the latest in my error log.
#0 /var/www/playground/vendor/laravel/framework/src/Illuminate/Foundation/Console/ServeCommand.php(29): Illuminate\Foundation\Console\ServeCommand->checkPhpVersion()
#1 /var/www/playground/vendor/laravel/framework/src/Illuminate/Console/Command.php(108): Illuminate\Foundation\Console\ServeCommand->fire()
#2 /var/www/playground/vendor/symfony/console/Symfony/Component/Console/Command/Command.php(241): Illuminate\Console\Command->execute(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#3 /var/www/playground/vendor/laravel/framework/src/Illuminate/Console/Command.php(96): Symfony\Component\Console\Command\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#4 /var/www/playground/vendor/symfony/console/Symfony/Component/Console/Application.php(892): Illuminate\Console\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#5 /var/www/playground/vendor/symfony/console/Symfony/Component/Console/Application.php(191): Symfony\Component\Console\Application->doRunCommand(Object(Illuminate\Foundation\Console\ServeCommand), Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#6 /var/www/playground/vendor/symfony/console/Symfony/Component/Console/Application.php(121): Symfony\Component\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#7 /var/www/playground/artisan(59): Symfony\Component\Console\Application->run()
#8 {main} [] []
The problem is with your School.php's relationship defination.
public function school()
{
return $this->hasOne('School');
}
By this you are telling laravel that this model has a one-to-one / one-to-many relationship with itself and this causes a recursive loop when School::all() is called. Once the loop exceeds the max allowed memory size as set in php.ini, it will return an empty response. Thats why you are getting a blank screen.
This relationship does not seem logical to me but if the schools are hierarchical, you should change the method name school() to something like parent() to avoid confusing laravel. Eg..
public function parent()
{
return $this->hasOne('School', 'parent_id');
}
class School extends Eloquent
{
protected $table = 'Schools';
public $timestamps = false;
protected $softDelete = false;
public function school()
{
return $this->hasOne('School');
}
}
You have a School object which has a one to one relationship with another school object? You also haven't defined the foreign key to the relationship
I think that laravel is just recursively loading school object after school object and then running out of memory before it can build an error. You can test this by commenting out the entire school() function and seeing what happens.
Another question can you access you apache error log?

Resources