Sorry if this is something really simple but I haven't been able to find an answer after hours of searching...
I have this object with relations:
$this->versionSelected = new StyleVersions();
$this->versionSelected = StyleVersions::with([
'colourways.colourway_yarns.yarns.spinners',
])->find($id);
Which is edited using wire:model:
wire:model="versionSelected.name"
and then verified:
protected $rules = [
'versionSelected.name' => 'required',
'versionSelected.factories_id' => 'required',
'versionSelected.yarn_transportation_cost' => 'required',
'versionSelected.yarn_transportation_currency' => 'required',
'versionSelected.accessories_cost' => 'required',
'versionSelected.accessories_currency' => 'required',
'versionSelected.transport_cost' => 'required',
'versionSelected.gmt_transportation_currency' => 'required',
'versionSelected.cmt' => 'required',
'versionSelected.gmt_weight' => 'required',
'versionSelected.area_office_commission' => 'required',
'versionSelected.notes' => 'required',
'versionSelected.style_version_prices' => 'required',
];
I then want to save that object to the database, but it is having issues with the relations.
$this->versionSelected->save();
When this is called I get the followin error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'style_version_prices' in 'field list' (SQL: update style_versions set style_version_prices = [{"id":10,"style_versions_id":4,"price":54.7,"notes":"Quo dolorum ab dolores.","created_at":"2022-02-25T10:19:23.000000Z","updated_at":"2022-02-25T10:19:23.000000Z"},{"id":18,"style_versions_id":4,"price":75,"notes":"Voluptatibus aut nihil.","created_at":"2022-02-25T10:19:23.000000Z","updated_at":"2022-02-25T10:19:23.000000Z"},
Is there a way I can update without it looking at the relations, which I can update separately? Thanks in advance! =D
EDIT:
Here is the code for the style_versions table:
Schema::create('style_versions', function (Blueprint $table) {
$table->id();
$table->foreignId('styles_id')->constrained()->onDelete('cascade');
$table->foreignId('factories_id')->constrained()->onDelete('cascade');
$table->text('name')->nullable();
$table->float('yarn_transportation_cost');
$table->float('gmt_weight');
$table->float('cmt');
$table->float('accessories_cost');
$table->float('transport_cost');
$table->text('notes')->nullable();
$table->float('area_office_commission')->default(0);
$table->float('yarn_cost');
$table->text('cmt_currency')->nullable();
$table->text('accessories_currency')->nullable();
$table->text('yarn_transportation_currency')->nullable();
$table->text('gmt_transportation_currency')->nullable();
$table->timestamps();
});
And the model:
class StyleVersions extends Model
{
use HasFactory;
protected $fillable = [
'styles_id',
'factories_id',
'yarn_transportation_cost',
'gmt_weight',
'cmt',
'accessories_cost',
'transport_cost',
'area_office_commission',
'notes',
'cmt_currency',
'accessories_currency',
'yarn_transportation_currency',
'gmt_transportation_currency',
'yarn_cost',
];
public function styles()
{
return $this->belongsTo(Styles::class);
}
public function factories()
{
return $this->belongsTo(Factories::class);
}
public function colourways()
{
return $this->hasMany(Colourways::class);
}
public function style_version_prices()
{
return $this->hasMany(StyleVersionPrices::class);
}
}
Related
So i want to store Parent data and array child data at the same time in laravel 9 rest api, but i dont even know how to format the array store, i was tried some looping code and still cant. the relationship was one parent has many child. i want to store like this
this what i expect store value
the parent model it just have name & class, and the child model was foreign parent_id & name. the model
here my controller
public function store(Request $request){
$this->validate($request, [
'parent_name' => 'required',
'class' => 'required',
'child.*' => 'array',
]);
$child = $request->child;
$chd = [];
foreach($child as $cd){
array_push($chd, Child::create([
'child' => $cd,
]));
}
$this->updates->create($request->all());
return $this->index();
}
here the migration :
Schema::create('parent', function (Blueprint $table) {
$table->increments('id');
$table->string('parent_name');
$table->string('class');
$table->timestamps();
});
Schema::create('child', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('parent_id')->unsigned()->index();
$table->foreign('parent_id')->references('id')->on('parent_id')->onDelete('cascade');
$table->timestamps();
});
}
You may want to try this
public function store(Request $request) {
$rules = [
'parent_name' => 'required|string|max:255',
'class' => 'required|string|max:255',
'child' => 'required|array',
'child.name' => 'required|string|max:255',
];
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
return response()->json(['error' => true, 'error_msg' => 'invalid input']);
}
DB::beginTransaction();
$parent = Parent::create([
'parent_name' => $request->parent_name,
'class' => $request->class,
]);
foreach ($request->child AS $child) {
$child = Child::create([
'parent_id' => $parent->id,
'name' => $child['name'],
]);
}
DB::commit();
return response()->json(['error' => false]);
}
So, I have a pivot table called user_filmscores, where the users can ''follow (watching, dropped, hold-on...)'' a film and add a rating on it.
In the userController I have this function:
public function userFilm(Request $request){
$data = $request->all();
$validator=Validator::make($data,[
'user_id' => 'required',
'film_id' => 'required',
'state' => 'required',
'score' => 'nullable'
]);
if($validator->fails()){
return response()->json([
'ok' => false,
'error' => $validator->messages(),
]);
}
$film = Film::find($data['film_id']);
$user = User::find($data['user_id']);
$filmId=$data['film_id'];
$userId=$data['user_id'];
//Check if the relationship exists (I tried many methods but always the same result with false)
/*$hasFilm = User::where('id', $data['user_id'])->whereHas('film', function ($q) use ($filmId) {
$q->where('id', $filmId);
})->exists();*/
$hasFilm = $user->film()->where('film_id', '=', $filmId)->exists();
/*$user->film()->sync($film->getKey(), [
'film_id' => $data['film_id'],
'user_id' => $data['user_id'],
'state' => $data['state'],
'score'=> $data['score']
]);*/
if(User::where('id', $userId)->where('id')){
$user->film()->attach($film->getKey(), [
'film_id' => $data['film_id'],
'user_id' => $data['user_id'],
'state' => $data['state'],
'score'=> $data['score']
]);
}else{
$user->film()->detach($film->getKey());
}
}
In the final part of the code, I want to check if the relationship between the user and the film exists, to make an action or another. But when I try to check if the relationship exists, it always returns me a false.
I thought to do it like, if there is a relationship, first delete the old relationship, and then create a new one.
I don't know if there is a better way to do it.
User model has this function:
public function film(){
return $this->belongsToMany('App\Models\Film', 'user_filmscores', 'user_id', 'film_id', 'state', 'score');
}
Film model has this function:
public function user(){
return $this->belongsToMany('App\Models\Film', 'user_filmscores', 'film_id', 'user_id', 'state', 'score');
}
Users table:
Films table:
User_filmscores table:
when I send data from form to database
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'fypp.joblisting' doesn't exist (SQL: select count(*) as aggregate from `joblisting` where `email` = )
this error occurs. In my database joblistings table exists but laravel looking for the singular name instead of the plural table name. Even I have created new model with new migration and everything but still facing this issue.
model code
class Joblisting extends Model
{
use HasFactory;
protected $fillable = [
'title',
'category',
'company',
'email',
'level',
'number',
'description',
];
}
controller code
class JoblistingController extends Controller
{
public function showForm()
{
return view('frontend.pages.addjob');
}
public function createjob(Request $request)
{
$this->validate($request,[
'title'=> 'required|string',
'category'=> 'required',
'company' =>'required',
'email' => 'required|unique:joblisting',
'level' => 'required',
'number' => 'required',
'description' => 'required',
]);
Joblisting::create([
'title' => $request->title,
'category' => $request->category,
'company'=> $request->company,
'email'=> $request->email,
'level'=> $request->level,
'number'=> $request->number,
'description'=> $request->description,
]);
return redirect('viewlist')->with('success', 'job posted successfully');
}
}
migration code
class CreateJoblistingsTable extends Migration
{
public function up()
{
Schema::create('joblistings', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('category');
$table->string('company');
$table->string('email');
$table->string('level');
$table->string('number');
$table->string('description');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('joblistings');
}
}
You have to use like this
'email' => 'required|unique:joblistings',
Laravel uses snake case, hence:
Fix 1:
use controller name as JobListingController
Fix 2:
in your model, add tthe following line:
protected $table = 'joblistings';
I am trying to follow this error but I don't know where it is that I need to create purchases. If someone could please help me know how to follow this error I would appreciate it.
Here is my Migration
public function up()
{
Schema::create('purchases', function (Blueprint $table) {
$table->increments('id');
$table->string('product');
$table->string('fname');
$table->string('lname');
$table->string('address');
$table->string('city');
$table->string('state');
$table->integer('zip');
$table->string('card');
$table->timestamps();
});
}
Here is my Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Purchase extends Model
{
public function addPurchase($body)
{
$this->purchases()->create(compact('fName'));
$this->purchases()->create(compact('lName'));
$this->purchases()->create(compact('address'));
$this->purchases()->create(compact('city'));
$this->purchases()->create(compact('state'));
$this->purchases()->create(compact('zip'));
$this->purchases()->create(compact('card'));
}
}
edit: I am trying to push all the above date to a mySQL database
Here is my controller store function
public function store(Purchase $purchase)
{
$this->validate(request(), ['fName' => 'required|min:3']);
$this->validate(request(), ['lName' => 'required|min:3']);
$this->validate(request(), ['address' => 'required']);
$this->validate(request(), ['city' => 'required']);
$this->validate(request(), ['state' => 'required']);
$this->validate(request(), ['zip' => 'required']);
$this->validate(request(), ['card' => 'required']);
$purchase->addPurchase(request('fName'));
$purchase->addPurchase(request('lName'));
$purchase->addPurchase(request('address'));
$purchase->addPurchase(request('city'));
$purchase->addPurchase(request('state'));
$purchase->addPurchase(request('zip'));
$purchase->addPurchase(request('card'));
return back();
}
As we've established in the comments, the error happens because $purchase variable in the controller is an instance of a Purchase query builder. And in your ->addPurchase() {...} method you're calling $this->purchase(), which is a nonexistant method on a query builder.
Now how to make this work. There's a lot of ways.
One would be to manually assign all properties to the model and call ->save() afterwards:
public function store(Purchase $purchase)
{
// ... validation
// Assign the properties
$purchase->fname = request('fName');
$purchase->lname = request('lName');
$purchase->address = request('address');
$purchase->city = request('city');
$purchase->state = request('state');
$purchase->zip = request('zip');
$purchase->card = request('card');
$purchase->save(); // Save to the database
return back();
}
Another would be to use mass assignment:
public function store(Purchase $purchase)
{
// ... validation
$purchase->forceCreate(request()->only([
'fName', 'lName', 'address', 'city', 'state', 'zip', 'card',
]));
return back();
}
Using forceCreate(...), which is same as ->create(...) except that it bypasses the $fillable array, which in this specific instance is OK, since a) we're manually telling it which fields are to be filled, with request()->only([fields]) b) you're performing validation before saving.
And there are more ways to do this, most of them well documented.
One last thing I would recommend is to perform validation with (technically) 1 line:
public function store(Purchase $purchase)
{
$this->validate(request(), [
'fName' => 'required|min:3',
'lName' => 'required|min:3',
'address' => 'required',
'city' => 'required',
'zip' => 'required',
'card' => 'required',
]);
// Save the model...
}
This way you would get all the errors (if something doesn't pass) in an array, rather than only the first one that didn't pass.
i am having trouble inserting data into my database according to my database structure. I have 3 tables. Company table Users table branches table.
Now this is how i made the relationship between these tables.
Company table and Users table have one to many relationship
Company table and Branches table have one to many relationship
Branches table and Users table have one to many relationsip
This is how my model looks like
PS: I am only a beginner with database and laravel
Company Model
public function branches()
{
return $this->hasMany('App\Branch');
}
public function users()
{
return $this->hasMany('App\User');
}
User Model
public function company()
{
return $this->belongsTo('App\Company')
->withTimestamps();
}
public function branches()
{
return $this->belongsTo('App\Branch')
->withTimestamps();
}
Branch Model
public function company()
{
return $this->belongsTo('App\Company');
}
public function users()
{
return $this->hasMany('App\User');
}
Now, when a user registers, only the company table is filled with it details but the user table and branch table is not filled and i get the error
"SQLSTATE[HY000]: General error: 1364 Field 'company_id' doesn't have a default value (SQL: insert into `branches` (`name`, `updated_at`, `created_at`) values (Virginia, 2017-10-14 03:19:38, 2017-10-14 03:19:38)) ◀"
This is how i save the data in the RegisterController
RegisterController
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'phone' => $data['phone'],
'password' => bcrypt($data['password']),
"company_id" => Company::create(
[
"name" => $data['rname'],
"email" => $data['remail'],
"phone" => $data['rphone'],
"address" => $data['raddress']
]
)->id,
"branch_id" => Branch::create (
[
"name" => $data['rbranch']
]
)->id
]);
}
You should try this may be its help for you:
protected function create(array $data)
{
$company = Company::create(
[
"name" => $data['rname'],
"email" => $data['remail'],
"phone" => $data['rphone'],
"address" => $data['raddress']
]);
Updated Answer
$branch = Branch::create (
[
"name" => $data['rbranch'],
"company_id" => $company->id
]
);
if(isset($company->id) && isset($branch->id)){
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'phone' => $data['phone'],
'password' => bcrypt($data['password']),
"company_id" => $company->id,
"branch_id" => $branch->id
]);
} else{
return redirect()->back()->withFlashDanger("company or branch no successfully insterted");
}
}
You need to create nullable foreign keys...
In your migration, use the ->nullable() function...
$table->integer('company_id')->unsigned()->nullable();
This will let you not include a company_id initially, the value will be null... without the nullable() the database will not allow null values...
Hope this helps.