How to insert in a translatable field? - php

Using Lumen 5.1, I'd like to know how to to CRUD on a translatable field, in my case it's name.
This is migration file
class CreateDomainHolidays extends Migration
{
protected $table = 'domain_holidays';
protected $app_table = true;
public function up()
{
Schema::create($this->getTable(), function (Blueprint $table) {
$table->increments('id');
$table->integer('domain_id')->unsigned()->nullable();
$table->foreign('domain_id')->references('id')
->on(self::getTableName('domains'))->onDelete('cascade');
$table->string('name')->nullable()->default('')->translatable = true;
$table->dateTime('start_date');
$table->dateTime('end_date');
$table->tinyInteger('half_day_start')->default(0);
$table->tinyInteger('half_day_end')->default(0);
$this->parenttable = $table;
});
$this->createTableWithTranslation($this->parenttable);
}
public function down()
{
$this->dropTranslationTable($this->getTable());
Schema::drop($this->getTable());
}
}
This is my model
class Holiday extends BaseModel
{
protected $table = 'domain_holidays';
protected $app_table = true;
public $timestamps = false;
protected $translation = true;
public function translations()
{
return $this->hasMany('App\Models\General\HolidayTranslations', 'parent_id');
}
}
class HolidayTranslations extends BaseTranslationModel
{
protected $table = 'domain_holidays_i18n';
protected $primaryKey = 'translation_id';
}
}
domain_holidays contains
id
domain_id
start_date
end_date
half_day_start
half_day_end
domain_holidays_i18n contains
translation_id
parent_id
lang
name
Something like this is not working
public static function setHoliday($domainId, $name, $startDate, $endDate, $halfDayStart, $halfDayEnd)
{
Holiday::unguard();
return Holiday::create([
'domain_id' => $domainId,
'name' => $name,
'start_date' => $startDate,
'end_date' => $endDate,
'half_day_start' => $halfDayStart,
'half_day_end' => $halfDayEnd
]);
}
Postman would return an error
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'name' in 'field list'

Related

Get all the genres that a movie belongs to in the Laravel REST API

Asside from the $movie data I want to also get all the genres that a movie belongs to following this path: 127.0.0.1:8000/api/movies/{id}. My foreign keys are in the separate table so how exactly I can achieve that? My migrations:
public function up()
{
Schema::create('genres', function (Blueprint $table) {
$table->id();
$table->string('name');
});
}
public function up()
{
Schema::create('movies', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->integer('status')->nullable()->default(0);
$table->string('image_path')->default('default.png');
});
}
public function up()
{
Schema::create('genre_movie', function (Blueprint $table) {
$table->foreignId('genre_id')->constrained()->cascadeOnDelete();
$table->foreignId('movie_id')->constrained()->cascadeOnDelete();
});
}
Movie model:
class Movie extends Model
{
use HasFactory;
public $timestamps = false;
protected $fillable = ['name', 'status', 'image_path'];
public function genres()
{
return $this->belongsToMany(Genre::class, 'genre_movie');
}
}
Genre model:
class Genre extends Model
{
use HasFactory;
public $timestamps = false;
protected $fillable = ['name'];
public function movies()
{
return $this->belongsToMany(Movie::class, 'genre_movie');
}
}
Movie Resource:
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'status' => $this->status,
'image_path' => url()->to('/images/' .$this->image_path),
];
}
Genre Resource:
public function toArray($request){
return [
'id' => $this->id,
'name' => $this->name,
];
}
Function in the controller which only returns $movie data:
public function show(Movie $movie)
{
return new MovieResource($movie);
}
I thought this would work:
public function show(Movie $movie)
{
return new MovieResource($movie->with('genres'));
}
But I receive this error: "message": "Property [id] does not exist on the Eloquent builder instance."
You can return JSON with a small change too.
public function showMovieAndGenre(Movie $movie)
{
$fullData = Movie::join('genres', 'genres.id', '=', 'movies.id')
->select([
'movies.id AS mid',
'genres.id AS gid',
'movies.name AS mname',
'genres.name AS gname',
'movies.status AS status',
'movies.image_path AS image_path'
])
->get();
return $fullData;
}
return $this->belongsToMany(Genre::class, 'genre_movie');
Consider using hasManyThrough https://laravel.com/docs/9.x/eloquent-relationships#has-many-through

How to save brand_id Laravel

trucks table have brand_id. When I create a truck I want to save the brand_id.
Truck one to one Brand.
Migration Brands
public function up()
{
Schema::create('brands', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
Migration Trucks
public function up()
{
Schema::create('trucks', function (Blueprint $table) {
$table->id();
$table->integer('brand_id');
$table->integer('year');
$table->string('owner_full_name');
$table->integer('number_of_owners')->nullable();
$table->text('comment')->nullable();
$table->timestamps();
});
}
Model Brand
class Brand extends Model
{
protected $table = 'brands';
protected $fillable = ['name'];
public function truck()
{
return $this->belongsTo(Truck::class);
}
}
Model Truck
class Truck extends Model
{
protected $table = 'trucks';
protected $fillable = [
'brand_id',
'year',
'owner_full_name',
'owner_numbers',
'comment'
];
public function brand()
{
return $this->hasOne(Brand::class);
}
}
Truck Form (I am using https://kristijanhusak.github.io/laravel-form-builder/) Form Builder
class TruckForm extends Form
{
public function buildForm()
{
$this
->add('brand_id', Field::SELECT, [
'empty_value' => 'Select Brand',
'choices' => Brand::pluck('name')->all()
])
->add('year', Field::NUMBER, [
'rules' => ['required', 'gt:1900', 'lte:' . Carbon::now()->year]
])
->add('owner_full_name', Field::TEXT, [
'rules' => ['required', new MinWordsRule(2)]
])
->add('number_of_owners', Field::NUMBER, ['rules' => 'nullable'])
->add('comment', Field::TEXTAREA, ['rules' => 'nullable'])
->add('Save or Create', Field::BUTTON_SUBMIT, [
'attr' => ['class' => 'btn btn-success']
]);
}
}
My need when create truck brand_id save being his brand
Truck Controller
public function create(FormBuilder $formBuilder)
{
$brandForm = $formBuilder->create(TruckForm::class, [
'method' => 'POST',
'url' => route('trucks.store')
]);
return view('landing.trucks.create', compact('brandForm'));
}
public function store(FormBuilder $formBuilder, Request $request)
{
$brandForm = $formBuilder->create(TruckForm::class);
$brandForm->redirectIfNotValid();
$object = new Truck();
$object->fill($request->all());
$object->save();
$object->brand()->save($request->input('brand_id'));
return redirect()->route('trucks.index');
}
First, make sure to validate your user inputs even if they came from an HTML select tag
//...
'brand_id' => 'required|exists:brands,id' // make sure your brand_id is a valid ID
//...
Then
Keep your controller simple
public function store(FormBuilder $formBuilder, Request $request)
{
$brandForm = $formBuilder->create(TruckForm::class);
$brandForm->redirectIfNotValid();
$object = new Truck();
// this line will map the brand_id attr to $obj->brand_id and link the 2 models to each others ...
$object->fill($request->all());
$object->save();
return redirect()->route('trucks.index');
}
Your relationships are switched around, as you can see here, since the Truck has the brand_id it should have the belongsTo and Brand should have the hasOne, like this:
Brand model:
class Brand extends Model
{
public function truck()
{
return $this->hasOne(Truck::class);
}
}
Truck model:
class Truck extends Model
{
public function brand()
{
return $this->belongsTo(Brand::class);
}
}
And as you can see here, you can simplify your store method to something like this:
public function store(FormBuilder $formBuilder, Request $request)
{
$form = $formBuilder->create(TruckForm::class);
$form->redirectIfNotValid();
Truck::create($form->getFieldValues());
return redirect()->route('trucks.index');
}
Or using the FormBuilderTrait:
use Kris\LaravelFormBuilder\FormBuilderTrait;
use App\Forms\TruckForm;
class TruckController extends Controller
{
use FormBuilderTrait;
public function store(Request $request)
{
$form = $this->form(TruckForm::class);
$form->redirectIfNotValid();
Truck::create($form->getFieldValues());
return redirect()->route('trucks.index');
}
}

ERROR SQLSTATE[HY000]: General error: 1364 Field 'name' doesn't have a default value (SQL: insert into `favorites` () values ())

I am trying to copy a station from the station repository and add it to my favorite repository. I am in a laravel rest API. Thanks for the help!
Here is my controller:
class FavoriteController extends Controller
{
private $favoriteRepository;
private $stationRepository;
public function __construct(FavoriteRepository $favoriteRepository, StationRepository $stationRepository)
{
$this->favoriteRepository = $favoriteRepository;
$this->stationRepository = $stationRepository;
}
public function store(int $station_id)
{
$favorite = array();
$favorite[] = $this->stationRepository->findByField("id", $station_id);
$this->favoriteRepository->create($favorite);
return response()->json($favorite, 201);
}
}
Here is the database for the favorites:
public function up()
{
Schema::create('favorites', function (Blueprint $table) {
$table->string('name');
$table->string('city');
$table->foreign('city')->references('name')->on('cities');
$table->integer('station_id')->unsigned();
$table->foreign('station_id')->references('id')->on('stations')->onDelete('cascade');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
#$table->boolean('is_private');
});
}
Here is my Favorite model
class Favorite extends Model
{
protected $fillable = ['station_id', 'user_id', 'updated_at', 'name', 'city'];
public $timestamps = false;
}
And I have both these methods in my repos:
function model()
{
return "App\\Station";
}
Try this
public function store($station_id)
{
$favorite = $this->stationRepository->where("id", $station_id)->first()->toArray();
$this->favoriteRepository->create($favorite);
return response()->json($favorite, 201);
}
}

column not found: 1054 Unknown column in laravel eloquent relationships

I'm trying to count number of schedules on a homecourt on current timestamp, now I have tried hasManyThrough in laravel between homecourt, userhomecourt, schedule but got this error
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'timeFrom' in 'where clause' (SQL: select count(*) as aggregate from `tblHomeCourts` where `homeCourtId` = 1 and `timeFrom` <= 1496207469 and `timeTo` > 1496207469)
I have these relationship in HomeCourt model
public function playerCount()
{
return $this->hasManyThrough(Schedule::class,UserHomeCourt::class,'homeCourtId','userHomeCourtId','homeCourtId');
}
where am I wrong here? please correct it out.
class HomeCourt extends Model
{
protected $table = 'tblHomeCourts';
protected $primaryKey = 'homeCourtId';
protected $appends = ['homeCourtProfilePicUrl'];
public static $snakeAttributes = false;
protected $fillable = [
'homeCourtName',
'cityId',
'homeCourtProfilePic',
'gameType',
'courtType',
'numberOfCourts',
'lights',
'membershipStatus',
'dayCost',
'address',
'lat',
'long',
'userId',
'homeCourtStatus',
];
protected $hidden = ['homeCourtProfilePic', 'created_at', 'updated_at', 'homeCourtStatus', 'userId', 'cityId'];
public function getHomeCourtProfilePicUrlAttribute()
{
return ($this->attributes['homeCourtProfilePic'] != "" || $this->attributes['homeCourtProfilePic'] != null) ? Constant::HOMECOURT_PROFILE_URL . $this->attributes['homeCourtProfilePic'] : null;
}
/*relation for there now*/
public function user()
{
return $this->belongsTo(User::class, 'homeCourtId', 'homeCourtId');
}
/*player count*/
public function playerCount()
{
return $this->hasManyThrough(Schedule::class,UserHomeCourt::class,'homeCourtId','userHomeCourtId','homeCourtId');
}
}

Laravel 4: Eloquent and relationships

I'm having troubles to setup the right Eloquent relationships (belongsTo, hasMany, ...) for a pivot table.
I will abbreviate code for clarity.
I have two important tables: 'parties' and 'p2p_relations'.
This is the migration for parties
public function up()
{
Schema::create('parties', function ($table) {
$table->increments('id');
$table->string('name');
$table->unsignedInteger('kind');
$table->timestamps();
$table->softDeletes();
$table->foreign('kind')->references('id')->on('kinds');
});
}
This is the migration for p2p_relations (party to party relations)
public function up()
{
Schema::create('p2p_relations', function ($table) {
$table->bigIncrements('id');
$table->unsignedInteger('context');
$table->unsignedInteger('reference');
$table->datetime('start');
$table->datetime('end')->nullable();
$table->unsignedInteger('kind')->nullable();
$table->timestamps();
$table->softDeletes();
$table->foreign('context')->references('id')->on('parties');
$table->foreign('reference')->references('id')->on('parties');
$table->foreign('kind')->references('id')->on('kinds');
});
}
The model for Party
class Party extends Ardent
{
use SoftDeletingTrait;
protected $softDelete = true;
protected $dates = ['created_at', 'updated_at', 'deleted_at'];
protected $table = 'parties';
public static $rules = array(
'name' => 'required',
'kind' => 'required|numeric'
);
}
The model for Relation
class Relation extends Ardent
{
use SoftDeletingTrait;
protected $softDelete = true;
protected $dates = ['created_at', 'updated_at', 'deleted_at'];
protected $table = 'p2p_relations';
public static $rules = array(
'context' => 'required|numeric',
'reference' => 'required|numeric',
'kind' => 'required|numeric',
'start' => 'required|date',
'end' => 'date'
);
}
How can I set relationships so I can associate parties as context or reference in a relationship.
I thought belongsTo will help like so in class Relation
public function context() {
return $this->belongsTo('Party', 'context', 'id');
}
public function reference() {
return $this->belongsTo('Party', 'reference', 'id');
}
But when I run this unit-test I get an error: Undefined property: Relation::$context
$context = new Party();
$context->name = 'Person A';
$context->kind = 1;
$context->save();
$ref = new Party();
$ref->name = 'Company B';
$ref->kind = 2;
$ref->save();
$relation = new Relation();
$relation->start = new DateTime();
$relation->context()->associate($context);
$relation->reference()->associate($ref);
$relation->kind = 3;
$relation->save();
Any thoughts? I'm really a newbie to this framework.
Thanks to the comments provided I've learned a lot :-)
Updated my Party Model:
public function references() {
return $this->belongsToMany('Party', 'p2p_relations', 'context', 'reference')
->withPivot('reference', 'start', 'kind')
->withTimestamps() ;
}
No Relation model needed.
The pivot table works perfectly.
Thanks

Categories