I have users table with hasMany educational backgrounds & educational awards. Then that educational backgrounds hasMany educational awards
Here's my Testcase when user uploads image my endpoint receives it
public function testuploadUsersImageEducationalAwards()
{
Storage::fake('public');
$photo = UploadedFile::fake()->create('photo.png')->size(25000);
$data = [
'photo' => $photo,
'award' => $this->faker->word,
'educational_background_id' => EducationalBackground::factory()->create()->id
];
$this->withoutExceptionHandling();
$response = $this->sendPostRequestToEndpoint($data, 200);
$data['file_name'] = $response['file_name'];
unset($data['photo']);
$response->assertJson($data)
->assertJsonStructure([
'id',
'award',
'photo',
'educational_background_id',
'created_at',
'updated_at',
]);
$this->assertDatabaseHas('users.educational_awards', $data);
}
Here's my endpoint with assert status 200
private function sendPostRequestToEndpoint(array $data, $status)
{
return $this->json("POST", '/api/users/educational-award/upload-picture', $data)->assertStatus($status);
}
UPDATE
Here's my EducationalBackgroundFactory
class EducationalBackgroundFactory extends Factory
{
protected $model = EducationalBackground::class;
public function definition()
{
return [
'user_id' => User::factory()->create()->id,
'studies_type' => $this->faker->randomElement([EducationalBackground::BASIC, EducationalBackground::SECONDARY, EducationalBackground::UNDERGRADUATE, EducationalBackground::GRADUATESCHOOL]),
'year' => Carbon::now()->format("Y"),
'course' => $this->faker->word,
];
}
}
Here's my EducationalBackground model
class EducationalBackground extends Model
{
use HasFactory;
const BASIC = "basic";
const SECONDARY = "secondary";
const UNDERGRADUATE = "undergrad";
const GRADUATESCHOOL = "grad";
protected $table = 'users.educational_backgrounds';
protected $fillable = [
'user_id',
'studies_type',
'year',
'course',
];
public function user()
{
return $this->belongsTo('App\Models\User', 'user_id');
}
public function educationalAwards()
{
return $this->hasMany("App\Models\Users\EducationalAward", "educational_background_id");
}
}
Here's my migration
public function up()
{
Schema::create('users.educational_backgrounds', function(Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->enum('studies_type', ['basic', 'secondary', 'undergrad', 'grad']);
$table->integer('year');
$table->string('course')->nullable();
$table->timestamps();
});
}
Here's my controller code
public function uploadUsersImageEducationalAwards(UserImageRequest $request, EducationalBackground $educational_background)
{
$uploaded_image = $request->photo->store('users/educational_awards');
$file_type = $request->photo->getClientOriginalExtension();
$file = EducationalAward::create([
'educational_background_id' => $educational_background->id,
'award' => $request->award,
'photo' => $uploaded_image,
]);
return response()->json($file, 200);
}
But this gives me 500 status which i found a way to log error in details. Here's an image for more clarity
remove unset function before sending response.
I'm using laravel 7
I need that if the user already took the test, load another different view
This is my test controller
public function index()
{
$categories = Category::with(['categoryQuestions' => function ($query) {
$query->orderBy('id')
->with(['questionOptions' => function ($query) {
$query->orderBy('id');
}]);
}])
->whereHas('categoryQuestions')
->get();
return view('client.test', compact('categories'));
}
public function store(StoreTestRequest $request)
{
$options = Option::find(array_values($request->input('questions')));
$result = auth()->user()->userResults()->create([
'total_points' => $options->sum('points')
]);
$questions = $options->mapWithKeys(function ($option) {
return [$option->question_id => [
'option_id' => $option->id,
'points' => $option->points
]
];
})->toArray();
$result->questions()->sync($questions);
return redirect()->route('client.results.show', $result->id);
}
}
This is the way the result table connects to the user table
This my migration to add relationship with a users table;
class AddRelationshipFieldsToResultsTable extends Migration
{
public function up()
{
Schema::table('results', function (Blueprint $table) {
$table->unsignedInteger('user_id');
$table->foreign('user_id', 'user_fk_773765')->references('id')->on('users');
});
}
}
Update your index method to check the results table. Assuming you have a Result model, for your results table.
public function index()
{
$existingTest = Result::where('user_id', Auth::user()->id)->first();
if(isset($existingTest->id)) {
//Return your other view or run logic specific to if the user has already done the test.
return view('client.test-complete');
}
$categories = Category::with(['categoryQuestions' => function ($query) {
$query->orderBy('id')
->with(['questionOptions' => function ($query) {
$query->orderBy('id');
}]);
}])->whereHas('categoryQuestions')
->get();
return view('client.test', compact('categories'));
}
I am working on a Laravel project. I am using Scout based on Algolia. But I struggling to apply whereIn on the relationships. I have 2 models as follow.
Place.php
class Place extends Model
{
use Searchable, Localizable;
protected $with = [
'images',
'phones',
'emails',
'categories'
];
protected $casts = [
'is_featured' => 'boolean'
];
public function categories()
{
return $this->belongsToMany(Category::class, 'place_category');
}
public function searchableAs()
{
return "places_index";
}
public function toSearchableArray()
{
$record = $this->toArray();
$record['_geoloc'] = [
'lat' => $record['latitude'],
'lng' => $record['longitude'],
];
$record['categories'] = $this->categories->map(function ($data) {
return [
'id' => $data['id'],
'en_name' => $data['en_name'],
'mm_name' => $data['mm_name'],
];
})->toArray();
unset($record['created_at'], $record['updated_at'], $record['latitude'], $record['longitude']);
unset($record['images'], $record['phones'], $record['emails']);
return $record;
}
}
Category.php
class Category extends Model
{
use Searchable;
protected $touches = [
'places',
];
public function places()
{
return $this->belongsToMany(Place::class, 'place_category');
}
}
Now, I am searching the Place models/ data filtering by category. As you can see, I have also indexed the categories with places in toSearchableArray method.
I am trying to achieve something like this.
Place::search($keyword)->whereIn('categories', ????);//how can I filter by the Ids here
How can I do that?
public function store(Request $request) {
$user = Book::create([
'user_id' => auth()->id(),
'name => $request->name,
'year => $request->year
)];
}
The above code is able to store into Database.
I want to know how to add below extra data TOGETHER.
I found out that merge was not working as it is not collection.
Tried to chain but was not working.
public function data() {
$array = [
'amount' => 30,
'source' => 'abcdef',
];
return $array;
}
You can catch create Event in Model.
This code may can help you.
/**
* to set default value in database when new record insert
*
*/
public static function bootSystemTrait()
{
static::creating(function ($model) {
$model->amount = 30;
});
}
You can write this code into your model. It will execute every time when you create record using Laravel model.
If you want to modify it you can use property into Model class. Something like this:
class TestClass extends Model
{
public static $amount = 0;
static::creating(function ($model) {
$model->amount = self::$amount;
});
}
Good Luck.
How can I create a database seeder factory for the following configuration?
User
// create_users_table.php
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
...
}
// User.php
public function notes()
{
return $this->morphMany('App\Note', 'noteable');
}
Complex
// create_complex_table.php
Schema::create('complex', function (Blueprint $table) {
$table->increments('id');
...
}
// Complex.php
public function notes()
{
return $this->morphMany('App\Note', 'noteable');
}
Notes
// create_notes_table.php
Schema::create('notes', function (Blueprint $table) {
$table->increments('id');
$table->integer('noteable_id');
$table->string('noteable_type');
...
}
// Note.php
public function noteable()
{
return $this->morphTo();
}
I am struggling to see the most robust way of ensuring that I am not just filling in random id's that may not exist.
I have improved upon HyperionX's answer and removed the static elements from it.
$factory->define(App\Note::class, function (Faker $faker) {
$noteable = [
App\User::class,
App\Complex::class,
]; // Add new noteables here as we make them
$noteableType = $faker->randomElement($noteables);
$noteable = factory($noteableType)->create();
return [
'noteable_type' => $noteableType,
'noteable_id' => $noteable->id,
...
];
});
Basically, we pick one of the noteable classes at random, then call it's own factory to get an instance of noteable, thus we get rid of the staticness of the OP's answer.
If you are using a morph map the given solutions won't work because the type won't be the same as the class name.
This will work in combination with a morph map.
Until Laravel 7
$factory->define(App\Note::class, function (Faker $faker) {
$noteable = $faker->randomElement([
App\User::class,
App\Complex::class,
]);
return [
'noteable_id' => factory($noteable),
'noteable_type' => array_search($noteable, Relation::$morphMap),
...
];
});
From Laravel 8
public function definition(): array
{
/** #var class-string<\App\Models\User|\App\Models\Complex> $noteable */
$noteable = $this->faker->randomElement([
App\Models\User::class,
App\Models\Complex::class,
]);
return [
'noteable_type' => array_search($noteable, Relation::$morphMap),
'noteable_id' => $noteable::factory(),
];
}
More information about morph map could be found here: https://laravel.com/docs/8.x/eloquent-relationships#custom-polymorphic-types
Although a bit more static than I would like, here is my solution:
I created exactly 20 models of each class, that way I could ensure the Notes that are created don't try to link to something that may not exist, leaving a dangling Note object.
// NotesFactory.php
$factory->define(App\Note::class, function (Faker $faker) {
$noteable = [
App\User::class,
App\Complex::class,
];
return [
'noteable_id' => $faker->numberBetween(0,20),
'noteable_type' => $faker->randomElement($noteable),
...
];
});
class CandidateFactory extends Factory {
protected $model = \App\Models\Candidate::class;
public function definition() {
$applicants = [
Contact::class,
Advertiser::class,
];
/** #var Model $applicant */
$applicant = Arr::random( $applicants )::factory()->create();
return [
'applicant_type' => $applicant->getMorphClass(),
'applicant_id' => $applicant->getKey(),
];
}
}
Then
/**
* #test
*/
public function candidate_has_applicants() {
$candidate = Candidate::factory()->create();
$this->assertInstanceOf( Candidate::class, $candidate );
$this->assertInstanceOf( Authenticatable::class, $candidate->applicant );
}
Updated Answer
If you don't care about controlling which morphable model is created:
public function definition()
{
return [
'content' => $this->faker->paragraph(),
'noteable_id' => function (array $attributes) {
return $attributes['noteable_type']::factory();
}),
'noteable_type' => $this->faker->randomElement([
Complex::factory(),
User::factory()
]),
'title' => $this->faker->sentence()
];
}
Original answer
I have another solution that does not imply the use of the randomElement, which is good by the way, but can be problematic when you need control on the morphable model that is being created. You still need to create model factories for the Note, User and Complex models. Then the run method of the Databaseeder class would look like this:
public function run()
{
$userNotes = Note::factory()->count(10)->for(
User::factory(), 'noteable'
)->create();
$complexNotes = Note::factory()->count(10)->for(
Complex::factory(), 'noteable'
)->create();
}
There is another approach by using the factory states. You still need to define model factories for your 3 models. Additionally you define two state transformation methods in the NoteFactory class.
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
class NoteFactory extends Factory
{
public function definition()
{
return [
'content' => $this->faker->paragraph(),
'title' => $this->faker->sentence()
];
}
public function forComplex()
{
return $this->state(function (array $attributes) {
return [
'noteable_type' => Complex::class,
'noteable_id' => Complex::factory()
];
});
}
public function forUser()
{
return $this->state(function (array $attributes) {
return [
'noteable_type' => User::class,
'noteable_id' => User::factory()
];
});
}
}
In this case the Databaseeder class run method would look like this:
public function run()
{
$userNotes = Note::factory()->count(10)->forUser()->create();
$complexNotes = Note::factory()->count(10)->forComplex()->create();
}
You could also do this without temporary variables like this:
$factory->define(App\Note::class, function (Faker $faker) {
return [
'noteable_type' => $faker->randomElement([
App\User::class,
App\Complex::class,
]),
'noteable_id' => function (array $note) {
return factory($note['noteable_type']);
},
...
];
})
You can create 10 user with 10 notes then create 10 complex with 10 notes.
like this 👇
public function run()
{
factory(User::class,10)->create()->each(
fn($user)=>
factory(Note::class,10)
->create(["noteable_id"=>$user,"noteable_type"=>User::class]),
);
factory(Complex::class,10)->create()->each(
fn($complex)=>
factory(Note::class,10)
->create(["noteable_id"=>$complex,"noteable_type"=>Complex::class]),
);
}
If you already created instances of the concrete Notables, perhaps via different factories, you may don't want to create any more new instances of it. In this case, you could extend Barracuda's solution:
$factory->define(App\Note::class, function (Faker $faker) {
$noteable = [
User::class,
Complex::class,
];
$noteableType = $faker->randomElement($noteable);
if ($noteableType === User::class) {
$noteableId = User::all()->random()->id;
} else {
$noteableId = Complex::all()->random()->id;
}
return [
'noteable_type' => $noteableType,
'noteable_id' => $noteableId,
...
];
});
I realise this would require a little bit of additional overhead to maintain the if/else branches but you won't have the problem of using IDs that don't exist.
Perhaps there is also a more elegant and generic way to get the Model::all() based on the Model::class, however I am unaware of it.
My preference is to use it this way, according to the factory structure, in new versions of Laravel.
$notable = $this->faker->randomElement([
[
'id' => User::all()->random(),
'type' => User::class,
],
[
'id' => Complex::all()->random(),
'type' => Complex::class,
]
]);
return [
'notable_id' => $notable['id'],
'notable_type' => $notable['type'],
...
];
You can extend model factory with state and pass to it related model, in state grab needed information and return merged results with default definition()
class NoteFactory extends Factory
{
protected $model = Note::class;
public function definition()
{
return [
'title' => $this->faker->sentence,
'note' => $this->faker->sentence,
//...
];
}
//new method that specify related model
public function forModel($model)
{
return $this->state(function () use ($model){
return [
'noteable_type' => $model->getMorphClass(), //return App\Lead etc
'noteable_id' => $model->id,
];
});
}
}
//usage
Note::factory()
->forModel($lead) //created method passing instance of App\Lead object
->create();