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.
Related
I cannot understand how to replicate model with unique slug field.
I see success message, but this code doesn't create additional row into DB table.
And no messages or exceptions in debugbar.
public function handle(Model $model)
{
$model->replicate(['slug']);
$model->slug = Str::slug($model->title, '-') . $model->id;
$model->save();
return $this->response()->success('Скопировано!')->refresh();
}
And if I add dd($model) somewhere in the middle it doesn't help me, because I don't see anything except Oops message.
Here is migration file
Schema::create('news_posts', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->integer('category_id')->unsigned();
$table->string('title', 255)->nullable();
$table->string('slug', 255)->unique();
$table->text('fulltext')->nullable();
$table->string('image', 255)->nullable();
$table->boolean('is_published')->default(false);
$table->timestamp('published_at')->nullable();
$table->timestamps();
$table->softDeletes();
$table->foreign('category_id')->references('id')->on('news_categories');
$table->index('is_published');
});
Model::replicate returns the new instance you are creating (replicating the old one). You are not doing anything with this new model; you have not assigned it to a variable. You are updating the slug field of the existing model instance ($model) and trying to save the existing model instance, not the new one.
Also the new model instance won't have an id until after it is saved, not before.
If this is how you generate slugs everywhere then you have nothing to update on the existing model and the slug field is not considered dirty since it is the same as it was before you set it; so no save actually happens (because there is nothing to update).
This is working.
$new = $model->replicate();
$new->slug = $new->slug . time();
$new->save();
This is my migration:
Schema::create('coupons', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name')->unique();
});
And this is my custom request:
use Illuminate\Validation\Rule;
public function rules()
{
return [
'name' => [
'required', 'string',
Rule::unique('coupons')
->where(function ($q) {
$q->where('name', 'OFFER-2020');
})
]
}
I am trying to block requests where coupon name field already exists in database table. Since OFFER-2020 row already exists in coupons table, it should block the request instead it passes validation.
Update
My input was OFFER 2020. And OFFER-2020 is value after transformation. I thought laravel was checking unique with OFFER-2020. Instead it was checking with both OFFER 2020 and OFFER-2020 by a and query. And that's why my unique was not working.
If you input is OFFER-2020. You will only need to set the correct column name which is the second parameter of the unique rules. This will check the coupons table, for a row with the same name as the input.
Rule::unique('coupons', 'name')
To make your input slugified, you can utilise the form request method prepareForValidation(), this can transform your data.
function prepareForValidation() {
$this->merge(['name' => Str::slug($this->get('name'))]);
}
Why did the previous version fail? As you can see here in the Unique class. If you do not provide a column it will default to id. So you previous query would end up looking something similar to this.
select * from coupons where id = 'OFFER-2020' and name = 'OFFER-2020'
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'],
...
]));
How i just want to ask if how can i be able to store another data if i have the same email. i've been making a renting system. after a costumer returned the items, he can be able to send request to rent again. but when i try to submit another form request again. it shows
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'annecurtis#gmail.com' for key 'borrower_requests_email_unique. i already removed the unique() in my the email column on my borrowersRequest table.
how can i do that?
well here is in my controller where costumer submit the data.
public function store(Request $request)
{
$rentform = new BorrowerRequest;
$rentform->user_id = $request->user_id;
$rentform->car_id = $request->car_id;
$rentform->borrowers_name = $request->borrowers_name;
$rentform->email = $request->email;
$rentform->return_date = $request->return_date;
$rentform->contact_number = $request->contact_number;
$rentform->request_status_id = $request->request_status_id;
$rentform->save();
$request->session()->flash('message', 'Your Request has been successfully submitted, please wait for a couple of hours for the approval');
return redirect('/borrowershistory');
anyone pls? thank you. by the way im using laravel and phpmyadmin here.
public function up()
{
Schema::create('borrower_requests', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('car_id');
$table->timestamps();
$table->string('borrowers_name', 50);
$table->string('email');
$table->bigInteger('contact_number');
$table->date('return_date');
$table->unsignedBigInteger('request_status_id')->default(0);
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('car_id')->references('id')->on('cars');
$table->foreign('request_status_id')->references('id')->on('request_statuses');
});
}
Drop the column borrower_requests_email_unique and add it again on the table of database if you don't have useful data now.Then it will be not giving issue.
I just started learning laravel by building a site with a payment platform.
After a successful payment i get an array returned when i do dd($paymentDetails);
I want to store the reference into the user database but sadly I don't know how to do that.
Here's my controller
public function handleGatewayCallback(Request $request)
{
$paymentDetails = Paystack::getPaymentData();
//dd($paymentDetails);
if ($request) {
$result = json_decode($request, true);
}
if (array_key_exists('data', $paymentDetails) && array_key_exists('status', $paymentDetails['data']) && ($paymentDetails['data']['status'] === 'success')) {
echo "Transaction was successful";
//Perform necessary action
}else{
echo "Transaction was unsuccessful";
}
// Now you have the payment details,
// you can store the authorization_code in your DB to allow for recurrent subscriptions
// you can then redirect or do whatever you want
}
I'll appreciate it if I am pointed to beginner friendly reading materials or tutorials that'll help.
You shouldn't store the reference directly on the users table, instead create an new table that set a relationship to users and stores the reference. This way a User -> HasMany -> Payments:
php artisan make:migration Payments --create=payments
// in your CreatePaymentsTable migration
$table->increments('id');
$table->unsignedInteger('user_id');
$table->unsignedInteger('reference');
...
// add more columns as needed
...
$table->foreign('user_id')->references('id')->on('users');
Create the Payment model and then add the relation in your User model:
public function payments()
{
return $this->hasMany(Payment::class);
}
Now you can store the reference in your controller as follows:
auth()->user()->payments()->create(['reference' => data_get($paymentDetails, 'data.reference')]);