I need to have a download history for each user that will use our system (basically, a system for users to download social media posts). I created a "DownloadHistory" model that contains the ID, Timestamp, download_history, and user_id fields. When I create a user, an instance of DownloadHistory should be automatically created and the users table updated to have the field download_history_id to contain the newly created DownloadHistory's id, as shown in my RegisterController:
$downloadHistory = DownloadHistory::create([ 'user_id' => $user->id ]); DB::table('users')->where('id', $user->id)->update(['download_history_id' => $downloadHistory->id]);
The problem is: I get an error which makes no sense to me:
The reason it doesn't make sense to me is that I never created download_history, but I did create download_history, so what is this? ? ? My DownloadHistory model is:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class DownloadHistory extends Model { use HasFactory; protected $fillable = [ 'user_id', ]; protected $casts = [ 'downloads' => 'array', ]; public function user() { return $this->belongsTo(User::class); } }
The migration I created for the table is:
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateDownloadHistoryTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('download_history', function (Blueprint $table) { $table->id(); $table->timestamps(); $table->json('history'); $table->integer('user_id'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('download_history'); } }
Add in the model
protected $table = 'download_history';
In Laravel, table names are assumed to be plural.
Reference: https://laravel.com/docs/9.x /eloquent#Table name
To fix this issue, use the
$table
attribute in the model.