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;
....
Related
I want to run Laravel Job. I'm using supervisord on Centos 7 (with php 7.3). And I want to make query in laravel Job Class. But when I try to make it, It's giving error in below. I wonder where I'm doing it wrong? My Error:
BadMethodCallException: Call to undefined method Illuminate\Database\Eloquent\Builder::all() in /home/merryedu/web/vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php:50
Stack trace:
#0 /home/merryedu/web/vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php(36): Illuminate\Database\Eloquent\Builder::throwBadMethodCallException('all')
#1 /home/merryedu/web/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php(1356): Illuminate\Database\Eloquent\Builder->forwardCallTo(Object(Illuminate\Database\Query\Builder), 'all', Array)
#2 /home/merryedu/web/app/Jobs/VideoLinkCheckerJob.php(35): Illuminate\Database\Eloquent\Builder->__call('all', Array)
#3 [internal function]: App\Jobs\VideoLinkCheckerJob->handle()
#4 /home/merryedu/web/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(32): call_user_func_array(Array, Array)
#5 /home/merryedu/web/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(90): Illuminate\Container\BoundMethod::Illuminate\Container\{closure}()
#6 /home/merryedu/web/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(34): Illuminate\Container\BoundMethod::callBoundMethod(Object(Illuminate\Foundation\Application), Array, Object(Closure))
#7 /home/merryedu/web/vendor/laravel/framework/src/Illuminate/Container/Container.php(576): Illuminate\Container\BoundMethod::call(Object(Illuminate\Foundation\Application), Array, Array, NULL)
#8 /home/merryedu/web/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php(94): Illuminate\Container\Container->call(Array)
#9 /home/merryedu/web/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(128): Illuminate\Bus\Dispatcher->Illuminate\Bus\{closure}(Object(App\Jobs\VideoLinkCheckerJob))
#10 /home/merryedu/web/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(104): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(App\Jobs\VideoLinkCheckerJob))
#11 /home/merryedu/web/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php(98): Illuminate\Pipeline\Pipeline->then(Object(Closure))
#12 /home/merryedu/web/vendor/laravel/framework/src/Illuminate/Queue/CallQueuedHandler.php(49): Illuminate\Bus\Dispatcher->dispatchNow(Object(App\Jobs\VideoLinkCheckerJob), false)
#13 /home/merryedu/web/vendor/laravel/framework/src/Illuminate/Queue/Jobs/Job.php(88): Illuminate\Queue\CallQueuedHandler->call(Object(Illuminate\Queue\Jobs\DatabaseJob), Array)
#14 /home/merryedu/web/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(327): Illuminate\Queue\Jobs\Job->fire()
#15 /home/merryedu/web/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(277): Illuminate\Queue\Worker->process('database', Object(Illuminate\Queue\Jobs\DatabaseJob), Object(Illuminate\Queue\WorkerOptions))
#16 /home/merryedu/web/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(118): Illuminate\Queue\Worker->runJob(Object(Illuminate\Queue\Jobs\DatabaseJob), 'database', Object(Illuminate\Queue\WorkerOptions))
#17 /home/merryedu/web/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(102): Illuminate\Queue\Worker->daemon('database', 'default', Object(Illuminate\Queue\WorkerOptions))
#18 /home/merryedu/web/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(86): Illuminate\Queue\Console\WorkCommand->runWorker('database', 'default')
#19 [internal function]: Illuminate\Queue\Console\WorkCommand->handle()
#20 /home/merryedu/web/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(32): call_user_func_array(Array, Array)
#21 /home/merryedu/web/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(90): Illuminate\Container\BoundMethod::Illuminate\Container\{closure}()
#22 /home/merryedu/web/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(34): Illuminate\Container\BoundMethod::callBoundMethod(Object(Illuminate\Foundation\Application), Array, Object(Closure))
#23 /home/merryedu/web/vendor/laravel/framework/src/Illuminate/Container/Container.php(576): Illuminate\Container\BoundMethod::call(Object(Illuminate\Foundation\Application), Array, Array, NULL)
#24 /home/merryedu/web/vendor/laravel/framework/src/Illuminate/Console/Command.php(183): Illuminate\Container\Container->call(Array)
#25 /home/merryedu/web/vendor/symfony/console/Command/Command.php(255): Illuminate\Console\Command->execute(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))
#26 /home/merryedu/web/vendor/laravel/framework/src/Illuminate/Console/Command.php(170): Symfony\Component\Console\Command\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))
#27 /home/merryedu/web/vendor/symfony/console/Application.php(921): Illuminate\Console\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#28 /home/merryedu/web/vendor/symfony/console/Application.php(273): Symfony\Component\Console\Application->doRunCommand(Object(Illuminate\Queue\Console\WorkCommand), Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#29 /home/merryedu/web/vendor/symfony/console/Application.php(149): Symfony\Component\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#30 /home/merryedu/web/vendor/laravel/framework/src/Illuminate/Console/Application.php(90): Symfony\Component\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#31 /home/merryedu/web/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(133): Illuminate\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#32 /home/merryedu/web/artisan(37): Illuminate\Foundation\Console\Kernel->handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#33 {main}
My system under;
Laravel 5.8,
PHP 7.3,
Queue on Database,
Supervisor installed,
Centos 7 latest version
"VideoLinkCheckerJob.php"
<?php
namespace App\Jobs;
use App\Http\Controllers\System\ConfigValue;
use App\Http\Controllers\System\VideoLinkCheckerController;
use App\Articles;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Log;
class VideoLinkCheckerJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* Create a new job instance.
*
* #return void
*/
public function __construct()
{
}
/**
* Execute the job.
*
* #return void
*/
public function handle()
{
Log::info("Video eğitim link kontrolcüsü başlatıldı!");
$articles = Articles::all();
foreach ($articles as $article) {
if($article->bot->lesson=='math') {
$status = VideoLinkCheckerController::videoLinkStatus(ConfigValue::get('a_video_host').$article->bot_video_id.".mp4");
Log::info($article->bot->code.' içindeki '.$article->google_video_id.' kodlu eğitimin durumu '.$status);
$article->video_link_status = $status;
$article->save();
} elseif ($article->lesson->code=='physics') {
$status = VideoLinkCheckerController::videoLinkStatus(ConfigValue::get('b_video_host').$article->bot_video_id.".mp4");
Log::info($article->bot->code.' içindeki '.$article->google_video_id.' kodlu eğitimin durumu '.$status);
$article->video_link_status = $status;
$article->save();
}
}
Log::info("Video eğitim link kontrolcüsü tamamlandı!");
}
}
And
"AdminArticleController.php"
namespace App\Http\Controllers;
use App\Bot;
use App\Category;
use App\Http\Controllers\System\ConfigValue;
use App\Http\Controllers\System\VideoLinkCheckerController;
use App\Jobs\VideoLinkCheckerJob;
use App\Articles;
use App\Tag;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
class AdminArticleController extends Controller
{
public function __construct()
{
$this->middleware('admin');
}
public function videoLinkChecker()
{
VideoLinkCheckerJob::dispatch();
return back()->with('success', 'İşlem başlatıldı tamamlandığında raporu Eğitimler sayfasında görüntüleyebilirsiniz!');
}
}
BadMethodCallException: Call to undefined method
Illuminate\Database\Eloquent\Builder::all() in
/home/merryedu/web/vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php:50
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
protected $table = 'articles';
protected $fillable = [
'bot_id', 'bot_video_id', 'category_id', 'url', 'title', 'description', 'duration', 'lesson', 'views', 'like', 'dislike', 'status', 'video_link_status',
];
public function category()
{
return $this->belongsTo('App\Category');
}
public function tag()
{
return $this->hasMany('App\ArticleTag');
}
public function bot()
{
return $this->belongsTo('App\Bot');
}
}
You are dispatching a job in a wrong way. Try like this
public function videoLinkChecker()
{
dispatch(new VideoLinkCheckerJob());
return back()->with('success', 'İşlem başlatıldı tamamlandığında raporu Eğitimler sayfasında görüntüleyebilirsiniz!');
}
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.
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
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',
];
}
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');