Skip to content

Instantly share code, notes, and snippets.

@Azer5C74
Last active December 14, 2023 21:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Azer5C74/5445423b2d6c39ff805d9905f413f3d3 to your computer and use it in GitHub Desktop.
Save Azer5C74/5445423b2d6c39ff805d9905f413f3d3 to your computer and use it in GitHub Desktop.
I wanted to insert few Article instances to my database when I was working on a Lumen Laravel project, each Article belongs to one Category and belongs to one User. These newly generated instances have to to be related to existent category_id and user_id values in the categories table and users table. so I found this simple trick and wanted to s…
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
use HasFactory;
protected $fillable=['title','slug','description','link','category_id','user_id'];
public function category(){
return $this->belongsTo(Category::class,'category_id');
}
public function user()
{
return $this->belongsTo(User::class);
}
}
<?php
namespace Database\Factories;
use App\Models\Article;
use App\Models\User;
user App\Models\Category;
use Illuminate\Database\Eloquent\Factories\Factory;
class ArticleFactory extends Factory
{
protected $model = Article::class;
public function definition(): array
{
return [
'title' => $this->faker->unique()->sentence,
'slug' => $this->faker->sentence,
'description' => $this->faker->sentence,
'link' => $this->faker->url,
'category_id' => Category::all()->random()->id,
'user_id' => User::all()->random()->id
];
// TODO: Implement definition() method.
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
/**
@mixin Eloquent
* Post
*
* @mixin Eloquent
* */
class Category extends Model
{
use HasFactory;
protected $fillable =['name','slug'];
public function articles()
{
return $this->hasMany(Article::class);
}
}
<?php
namespace App\Models;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Laravel\Lumen\Auth\Authorizable;
class User extends Model implements AuthenticatableContract, AuthorizableContract, JWTSubject
{
use Authenticatable, Authorizable, HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email','password', 'isAdmin'
];
public function articles()
{
return $this->hasMany(Article::class);
}
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = [
'password',
];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment