I want to insert with a form into two tables that are related with a foreign key,
First you need to create an order with customername, and then be forwarded to next form to insert multiple articles.
This is how my tables are made:
Schema::create('returnorders', function (Blueprint $table) {
$table->increments('id');
$table->string('firmaname');
$table->string('contacperson');
$table->string('email')->unique();
$table->string('ordernumber');
$table->string('customername');
$table->timestamps();
});
Schema::create('returnarticles', function (Blueprint $table) {
$table->increments('id');
$table->integer('order_id')->unsigned();
$table->foreign('order_id')->references('id')->on('returnorders');
$table->string('articlenumber');
$table->string('return_quantity');
$table->string('return_quality');
$table->string('return_reason');
$table->string('images');
});
My question is now, can i make one form where i can put multiple articles or should I make two forms, and that you will be forwarded from the first one to the next one?
My second question is, can I do this in one function in my controller or should i make two functions?
Help me out please, and if it's possible show me how to make my function.
Thanks
If your question is how to save these related models, then you should look at the documentation on Inserting and Updating related models:
Documentation
Your code could look something like this:
$returnOrder = ReturnOrder::create([
'firmaname' => $validatedInput['firmaname'],
'contactperson' => $validatedInput['contactperson'],
....
]);
$returnOrder->returnArticles()->save(ReturnArticle::create([
'articlenumber' => $validatedInput['articleNumber'],
...
]));
Related
In laravel 9 I have table pivot table defined :
Schema::create('article_vote', function (Blueprint $table) {
$table->id();
$table->foreignId('article_id')->references('id')->on('articles')->onUpdate('RESTRICT')->onDelete('CASCADE');
$table->foreignId('vote_id')->references('id')->on('votes')->onUpdate('RESTRICT')->onDelete('CASCADE');
...
});
and having in both models methods with belongsToMany
I can refer articles of a vote as :
$voteArticles = $vote->articles;
I got all related articles, but how can O get only 1 row if I have $articleId ?
Thanks!
That can be achieved in a number of ways by querying the relations:
$vote->articles()->where('id', $articleId)->first();
$vote->articles()->whereKey($articleId)->first();
$vote->articles()->find($articleId);
$vote->articles()->findOrFail($articleId);
Or in your example, you already have a collection of articles. We can also do this:
$vote->articles->find($articleId);
$vote->articles->findOrFail($articleId);
I have two tables transactions and transaction_allocations. One transaction can have many allocations.
Transaction Model
Schema::create('transactions', function (Blueprint $table) {
$table->bigIncrements('id');
$table->timestamps();
$table->foreignId('contact_id')->constrained();
$table->decimal('amount',19,4)->nullable();
});
Allocation Model
Schema::create('transaction_allocations', function (Blueprint $table) {
$table->bigIncrements('id');
$table->timestamp('created_at');
$table->foreignId('transaction_id')->nullable()->constrained();
$table->foreignId('bill_id')->nullable()->references('id')->on('bills');
$table->decimal('amount',19,4)->nullable();
});
Relationship in Transaction Model
public function allocations(){
return $this->hasMany(TransactionAllocation::class);
}
I need to query all transactions where the transaction amount is greater than the sum of all allocated amounts for that transaction. (Basically finding transaction which has unallocated balances).
Transaction::where('contact_id',$id)->where('amount','>',sum of allocations)->get();
How do I achieve it?
I was able to create an accessor to do this calculation and find an unallocated amount. But seems like accessors cannot be used in where. I don't want to load all transactions and then filter it as it will be too much.
I want to query and get filtered lines directly. How do I do it?
I think Having Raw is better to compare two column.
Transaction::where('contact_id',$id)
->with('allocations')
->whereHas("allocations",function ($query){
$query->havingRaw('transactions.credit>sum(amount)');
$query->groupBy('transaction_id');
})->orDoesntHave("allocations")
->get();
if query fails then try to 'strict' => false in database.php for mysql connection
I use laravel-nestedset for creating the category of articles.
Laravel: 8 / laravel-nestedset: 5.0.3
Table categories
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
NestedSet::columns($table);
$table->boolean('publish')->default(true);
...
Table articles
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->integer('category_id')->unsigned()->nullable();
$table->foreign('category_id')->references('id')->on('categories');
...
I have created a branch and a sub-branch in the category table like this:
news > politics
I have also created two articles and insert them into the 'news' branch and 'politics' branch.
article1 in news
article2 in politics
Everything works!
Now I have a scenario. I want to get all the articles that are only in the published categories. (publish = 1).
I try this:
$query = \App\Article;
$query->where(function($query)
{
$query->whereHas('category' , function ($query) {$query->where('publish' , true ); });
});
However, this code works only for the current article category (not for the parent of that category).
Let me explain more with an example.
pulish in "news" is false. (pulish = 0)
pulish in "politics" is true. (pulish = 1)
Now I want to get all articles with (pulish=1) in its category. The above query code returns me 'article2.' I expect no article to be returned to me. Because even "politics" is publish=1, its parent (news) is publish=0, so related articles should not be published. How can change the query code to support the parent (or even more its top parents)?
Thank you in advance for the assistance.
I am currently learning Laravel and I seem to not be able to wrap my head around a problem.
I am trying to create a quotation and invoice solution for a company that has dealers selling their product.
So what I have is a salesperson that has created a client using a form. The input is stored in a client table.
Schema::create('clients', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('system_id');
$table->string('name')->nullable();
$table->string('contact')->nullable();
$table->string('number')->nullable();
$table->string('email')->nullable();
Part of the form the salesperson selects the "system" that they want to quote the client on, this is the system_id above.
The user_id above refers merely to the salesperson that created the client.
Here is my products migration
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->integer('group');
$table->string('code');
$table->string('name');
$table->double('price');
$table->timestamps();
});
The client is stored successfully. Afterwards I use an if statement to determine which route to follow to configure the system.
if ($data['system_id'] == 1){
return redirect(route('system.824'))->with('success', 'Customer details have been saved.');
}elseif($data['system_id'] == 2){
return redirect(route('system.32'))->with('success', 'Customer details have been saved.');
}elseif ($data['system_id']==3){
return redirect(route('system.500'))->with('success', 'Customer details have been saved.');
}
The routes above goes to a certain function inside my SystemsController, here I retrieve the required "groups" as referred to above in my products migration.
These groups are used to configure the systems.
After the systems are configured the data is sent back to the SystemsController for me to perform the required validation and further logic for the configuration on the input received.
After the system is configured it is then sent to the SystemsController where I need to perform some logic based on the form input.
My issue is the accessing the client_id in the SystemsController so I can store the input received into the pivot table I created.
The client_id hasMany products
The products hasMany clients
I need to use the pivot table to keep track of what was quoted on in the configuration for that client. The pivot table will contain the client_id and the product_id with a a final column to save the quantity.
What am I missing here?
Thank you again.
As mentioned in my comments, you could send more data inside the with, either as an array or concatenating more withs.
return redirect(route('system.32'))->with('success', 'Customer details have been saved.')->with('user_id', $userId);
OR
return redirect(route('system.32'))->with(['success' => 'success message', 'user_id' => $userId]);
Referring to your comment, if you want to pass data inside the route action, you would need your route set up like so:
Route::get('path/to/your/route/system_input/{infoId}', 'SystemController#getInput')->name('system.input')
The method in SystemController should accept the parameter.
public function getInput($infoId) {
Then, in your redirect route:
return redirect(route('system.input', ['infoId' => $info->id]) );
Now you will have access to the infoId in your getInput method via $infoId.
I have this table :
public function up()
{
Schema::create('edition', function (Blueprint $table) {
$table->increments('id');
$table->integer('volume');
$table->text('cover')->nullable();
$table->enum('number', ['1', '2']);
$table->timestamps();
});
Schema::table('journal', function(Blueprint $table) {
$table->foreign('id_edition')->references('id')->on('edition')->onDelete('cascade')->onUpdate('cascade');
});
}
I wanted to make the combination of column Volume and Number as a unique key. For example, there is a data "Volume 1, Number 1" and when user insert the same combination it will throw an error message that the data already exist. Is there a way I can do this in Laravel ?
Just include the following snippet inside the up() method
$table->unique(['volume','number']);
By having this constraint set, if you insert 'Volume 1 , Number 1` once it'll be fine. However, if you try to do the same again, it'll throw an error.
Conditions:
You are using some good DBMS, such as MySQL and not SQLITE
You successfully migrated this change into the database.
You can also use uniquewith-validator package that allows you to validate a unique combination of fields like this
'field1' => 'required|unique_with:table_name,field2'
The above code will check if the combination of field1 and field2 is unique in the table with the given table_name.