MorphMany laravel relation does not work for some reason - laravel

I am using laravel 5.6 version, here is my Test model file
<?php
namespace App\Model\data\Models;
use Illuminate\database\Eloquent\Model;
class Test extends Model
{
protected $guarded = ['id'];
protected $table = 'tests';
/*
* Test - TestTranslation relation
* Test has many translations
*/
public function translations()
{
return $this->hasMany('App\Model\Data\Models\TestTranslation');
}
/*
* Test - Image relation
* Test can have an thumbnail
*/
public function thumbnails()
{
return $this->morphMany('App\Model\Data\Models\Image', 'type');
}
}
Here is my Image model
<?php
namespace App\Model\Data\Models;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
protected $guarded = ['id'];
protected $table = 'images';
/*
* Image belongs to Post, Account, Comment
*/
public function type()
{
return $this->morphTo();
}
}
Here is my Database scheme for Images table:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateImagesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('images', function (Blueprint $table) {
$table->increments('id');
$table->string('path');
$table->enum('type', ['avatar', 'thumbnail', 'generic'])->default('generic');
$table->integer('type_id')->unsigned()->nullable();
$table->enum('type_type',[
"Account",
"Comment",
"Post",
"Skill",
"Test"
])->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('images');
}
}
In AppServiceProvider I linked 'Test' to my model file:
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\ServiceProvider;
use Laravel\Dusk\DuskServiceProvider;
use Illuminate\Database\Eloquent\Relations\Relation;
use App\Model\Data\Models\Account;
use App\Model\Data\Models\EmailChangeConfirmation;
use App\Model\Observers\Common\AccountObserver;
use App\Model\Observers\Common\EmailChangeConfirmationObserver;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
Schema::defaultStringLength(191);
Relation::morphMap([
'Account' => 'App\Model\Data\Models\Account',
'Comment' => 'App\Model\Data\Models\Comment',
'Post' => 'App\Model\Data\Models\Post',
'Skill' => 'App\Model\Data\Models\Skill',
'Test' => 'App\Model\Data\Models\Test'
]);
if(env('APP_ENV') != 'testing') {
Account::observe(AccountObserver::class);
EmailChangeConfirmation::observe(EmailChangeConfirmationObserver::class);
}
}
/**
* Register any application services.
*
* #return void
*/
public function register()
{
if ($this->app->environment('local', 'testing')) {
$this->app->register(DuskServiceProvider::class);
}
}
}
As you can see, I have more morhpMany types, and all of them works fine. But for some reason, this Test relation that I added recently always returns an empty collection, even tough I am sure that test has thumbnails. Cause:
in this screenshot, I have records in database that each test has two images. Their ID matches ids of created tests and type is "Test". I tried to clear all caches, run composer dump-autoload but none of them helped.
Maybe someone can help identify what is wrong here? Because as I said before other types as Post, Account works fine.

Related

Image value should be null when image is not uploaded

Employee Controller
<?php
namespace App\Http\Controllers;
use App\Talent\Employee\Requests\EmployeeCreateRequest;
use App\Talent\Employee\EmployeeManager;
use Illuminate\Http\Response;
use App\Talent\User\UserManager;
use App\Talent\Documents\DocumentManager;
use Illuminate\Support\Facades\Hash;
class EmployeeController extends Controller
{
public function __construct(private EmployeeManager $employeeManager,private UserManager $userManager,private DocumentManager $documentManager)
{
}
public function store(EmployeeCreateRequest $request){
$validated = $request->validated();
$userArray=[
'name'=>$validated['first_name']." ".$validated['last_name'],
'email'=>$validated['email'],
'password'=>Hash::make("Introcept#123"),
'role'=>'user'
];
$userCreate=$this->userManager->store($userArray);
return $this->employeeStore($validated,$userCreate,$request);
}
public function employeeStore($validated,$userCreate,$request){
if($request->hasFile($validated['avatar']))
{
$validated['avatar']=$validated['avatar']->store('employeeimages','public');
}
else
{
$validated['avatar']='null';
}
$userId=$userCreate->id;
$userIdArray=[
'user_id'=>$userId,
'status'=>'Active',
];
$employeeArray=array_merge($validated,$userIdArray);
$employeeCreate=$this->employeeManager->store($employeeArray);
$employeeId=$employeeCreate->id;
foreach($validated['documents'] as $document){
$name=$document->getClientOriginalName();
$type=$document->getClientMimeType();
$path=$document->store('employeedocuments','public');
$documentArray=[
'employee_id'=>$employeeId,
'original_name'=>$name,
'type'=>$type,
'path'=>$path,
];
$documentCreate=$this->documentManager->store($documentArray);
}
return response([
'userId'=>$userId,
'employeeId'=>$employeeId,
'message'=>'Personal detail added successfully',
],Response::HTTP_OK);
}
}
Employee.php
<?php
namespace App\Talent\Employee\Model;
use App\Talent\Documents\Model\Document;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Employee extends Model
{
use HasFactory;
protected $fillable = [
'first_name',
'last_name',
'email',
'contact_number',
'date_of_birth',
'current_address',
'pan_number',
'bank_account_number',
'avatar',
'status',
'user_id',
];
**EmployeeRequest.php**
<?php
namespace App\Talent\Employee\Requests;
use Illuminate\Foundation\Http\FormRequest;
class EmployeeCreateRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array<string, mixed>
*/
public function rules()
{
return [
'first_name'=>'required|string',
'last_name'=>'required|string',
'email'=>'required|email|unique:employees,email',
'contact_number'=>'required|string',
'date_of_birth'=>'required|date',
'current_address'=>'required|string',
'pan_number'=>'string|nullable',
'bank_account_number'=>'string|nullable',
'avatar' => 'nullable|image|mimes:jpg,jpeg,png',
'documents'=>'required',
'documents.*'=>'max:5000|mimes:pdf,png,jpg,jpeg',
];
}
public function messages()
{
return [
'documents.max' => "Error uploading file:File too big.Max file size:5MB",
];
}
}
EmployeeMigration
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('employees', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained('users')->restrictOnDelete();
$table->string('status');
$table->string('first_name');
$table->string('last_name');
$table->string('email')->unique();
$table->string('contact_number');
$table->date('date_of_birth');
$table->string('current_address');
$table->string('pan_number')->nullable();
$table->string('bank_account_number')->nullable();
$table->string('avatar')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('employees');
}
};
I am trying to create an API that stores employee personal details into the database. Here, image field is optional so I made avatar field nullable in both migration and validation request as well. But when I try save details into the database without uploading image it shows undefined avatar. I don't know what happening here any help or suggestions will be really appreciated. Thank you.
You are using the string value of null instead of the keyword null.

Laravel 8 Invalid Date time while seeding

I am new to laravel , I receive error while trying to seed data, I have done it successfully in two different tables but I am stuck at this one :
Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
use HasFactory;
public $timestamps = false;
protected $fillable = [
'Pmid',
'Ministry',
'P_name',
'Budget',
];
protected $casts = [
'Registered_at' => 'datetime',
];
}
Factory
<?php
namespace Database\Factories;
use App\Models\Project;
use Illuminate\Database\Eloquent\Factories\Factory;
class ProjectFactory extends Factory
{
protected $model = Project::class;
/**
* Define the model's default state.
*
* #return array
*/
public function definition()
{
return [
'Pmid' => $this->faker->unique()->name(),
'Ministry' => $this->faker->name(),
'P_name' => $this->faker->name(),
'Budget' => $this->faker->name(),
'Registered_at' => now(),
];
}
}
Seeder
<?php
namespace Database\Seeders;
use App\Models\Project;
use Illuminate\Database\Seeder;
class ProjectTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
Project::factory()->count(20)->create();
}
}
Migration
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateProjectsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('projects', function (Blueprint $table) {
$table->increments('id');
$table->string('Pmid')->unique();
$table->string('Ministry');
$table->string('P_name');
$table->integer('Budget');
$table->timestamp('Registered_at');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('projects');
}
}
error
Illuminate\Database\QueryException
SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: 'Mathias Kuhlman' for column laravel.projects.Budget at row 1 (SQL: insert into projects (Pmid, Ministry, P_name, Budget, Registered_at) values (Nicholas Mayer, Ms. Donna Strosin, Hermann Bins, Mathias Kuhlman, 2021-12-05 08:36:39))
You're using
'Budget' => $this->faker->name(),
to create the data, but your migration shows that that column should be an integer :
$table->integer('Budget');
I suspect you've just copied and pasted the faker rows without changing the type of value being faked.

Trouble creating Laravel relationship

So I'm trying to have plans associated to the current user.
I have modal and migration called Plan. I have a method called user that I use the belongsTo() to get all the users that's associated to that plan. I'm not sure why its not working
Modal
namespace App\Models;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Plan extends Model
{
use HasFactory;
protected $fillable = [
'name',
'slug',
'stripe_plan',
'cost',
'description'
];
public function getRouteKeyName()
{
return 'slug';
}
public function user()
{
return $this->belongsTo(User::class);
}
}
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePlansTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('plans', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('slug')->unique();
$table->string('stripe_plan');
$table->float('cost');
$table->text('description')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('plans');
}
}
I call the Plan model from my controller
controller that calls the model
the view that i call the users method
It show blanks
the output on the screen
You didn't load the relationship. You can use the with() to achieve this.
<?php
// controller
class PlanController extends Controller {
public function method(){
$plans = Plan::with('user')->get();
// Continue with Code
// if you use compact to pass data to the view
// else $plans = Plan::all();
// views('view_name', ['plans' => $plans] should word just fine
}
}

SQLSTATE[42804] Error when trying to heroku run php artisan migrate

I've been trying to heroku run php artisan migrate from AWS Cloud9 without any success. How can I fix this problem? I would appreciate it very much if someone could help me. Thanks a lot!
I get three errors, all of which are saying
SQLSTATE[42804]: Datatype mismatch: 7 ERROR: column "administered" cannot be cast automatically to type smallint
HINT: You might need to specify "USING administered::smallint"
The migration file in question is as follows:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class ChangeFilariasisMedicationsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('filariasis_medications', function (Blueprint $table) {
$table->dropColumn('administered');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('filariasis_medications', function (Blueprint $table) {
$table->smallInteger ('administered');
});
}
}
Here is the related model.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
// 追加
use App\AdministeredDate;
use App\User;
use Illuminate\Notifications\Notifiable;
use App\Notifications\ReminderMail;
class FilariasisMedication extends Model
{
protected $fillable = [
'start_date',
'number_of_times',
'counter',
'administered'
];
protected $dates = [
'start_date',
];
use Notifiable;
/**
* この投薬スケジュールを所有するユーザ(Userモデルとの関係を定義)
*/
public function medication_user()
{
return $this->belongsTo(User::class);
}
/**
* この投薬スケジュールに属する投薬確定日(AdministeredDateモデルとの関係を定義)
*/
public function administered_date()
{
return $this->hasMany(AdministeredDate::class);
}
}
Current description of filariasis_medications table:
mysql> describe filariasis_medications;
enter image description here
You put a space before the parenthesis in your migration, remove it.
from $table->smallInteger ('administered');
to $table->smallInteger('administered');

postman 404 Not Found

I'm a beginner in laravel API I want to display list of articles (method index),I already created model Article, but I can not.
Hi, I'm a beginner in laravel API I want to display list of articles (method index),I already created model Article, but I can not.
ArticleController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Article;
use App\Http\Resources\Article as ArticleResource;
class ArticleController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$articles= Article::paginate(15);
return ArticleResource::collection($articles);
}
create_table_articles
public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('body');
$table->timestamps();
});
}
AppServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
Schema::defaultStringLength(191);
}
ArticlesTableSeeder
<?php
use Illuminate\Database\Seeder;
class ArticalesTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
factory(App\Article::class,30)->create();
}
}
ArticleFactory.php
<?php
/* #var $factory \Illuminate\Database\Eloquent\Factory */
use Faker\Generator as Faker;
$factory->define(App\Article::class, function (Faker $faker) {
return [
'title' => $faker->text(50),
'body' => $faker->text(200)
];
});
App\Resources\Article.php
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class Article extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function toArray($request)
{
return parent::toArray($request);
}
}
DatabaseSeeder.php
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$this->call(ArticalesTableSeeder::class);
}
}
routes/api.php
//list
Route::get('articles','ArticleController#index');
//list single
Route::get('article/{id}','ArticleController#show');
//create article
Route::post('article','ArticleController#store');
//update articles
Route::put('article','ArticleController#store');
//delete article
Route::delete('articles','ArticleController#destroy');
Laravel automatically prefixes routes in the routes/api.php file with the route prefix /api
You need to make a request to:
http://127.0.0.1:8000/api/articles
Rather than
http://127.0.0.1:8000/articles
You can change this in your RouteServiceProvider if your prefer:
https://github.com/laravel/laravel/blob/master/app/Providers/RouteServiceProvider.php#L66-L72

Resources