submit data with the same email in database - laravel

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.

Related

update content of stored column in laravel controller

I have a table with 3 columns:
firstname
lastname
fullname
in migration:
Schema::create('owners', function (Blueprint $table) {
$table->id();
$table->string('firstname',20);
$table->string('lastname', 20);
$table->string('fullname')->storedAs('CONCAT(firstname,lastname)');
$table->timestamps();
});
the problem is that i want to change the concatenation order in the controller i tried to use db statement but it doesn't work
-in the controller:
$owners= Owner::findOrFail($id);
$owners->update([
'firstname'=>$request['firstname'],
'lastname' =>$request['lastname'],
]);
DB::statement('UPDATE owners SET fullname AS CONCAT(lastname,firstname) STORED WHERE ID=1 ');
I don't want to just use a simple concatenation because the user can change the firstname or the lastname and the order that's why I used storedAs()
any ideas please?
The storedAs method in the migration creates a generated column in mysql. The value is automatically generated from the column values of the firstname and the lastname. There's no way you can change this via an UPDATE statement. You'd have to use an ALTER TABLE statement, which would be horrifically bad practice.
If I were you, I'd keep full name display as a model method so you could access it by using $owner->fullNameFirstLast() or $owner->fullNameLastFirst()
What you should do is create a new migration in order to change the column, the code would be something like this:
Schema::table('owners', function (Blueprint $table) {
$table->string('fullname')->storedAs('CONCAT(lastname,firstname)');
});
This way the column will be changed on a database level, and no need for the controller query you have added
Simply try this
1- update your migration to
Schema::create('owners', function (Blueprint $table) {
$table->id();
$table->string('firstname',20);
$table->string('lastname', 20);
$table->string('fullname', 56);
$table->timestamps();
});
2- in your controller
$owners= Owner::findOrFail($id);
$first_name = $request->firstname ?? $owners->firstname;
$last_name = $request->lastname ?? $owners->lastname;
$full_name = $first_name.' '.$last_name;
$owners->update([
'firstname'=>$first_name,
'lastname' =>$last_name,
'fullname' =>$full_name,
]);
You can also write it this way
DB::statement(DB::raw("UPDATE owners SET firstname = '".$first_name."', lastname = '".$last_name."', fullname = '".$full_name."' WHERE id = $id"));
And the same way for your Create function as well

Keeping track of a variable from one controller to another

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.

cannot replicate model with unique slug field

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();

Eloquent using wrong key for some tables

Using: Laravel 5.5
I Constructing addresses using some address elements (like: district, area, zip etc) as dropdowns & also some user inputs.
I have 5 address element & one of their schema is:
Schema::create('address_districts', function (Blueprint $table) {
$table->increments('id');
$table->integer('admin_id')->unsigned();
$table->string('name');
$table->timestamps();
$table->foreign('admin_id')->references('id')->on('admins');
});
This is for Districts, & I have another 3 exactly same like this called, address_thanas, address_areas, address_building_names & address_zips;
The only exception for the last one is that has code instead of name on other tables:
Schema::create('address_zips', function (Blueprint $table) {
$table->increments('id');
$table->integer('admin_id')->unsigned();
$table->string('code'); // Look other table has name here........
$table->timestamps();
$table->foreign('admin_id')->references('id')->on('admins');
});
I store constructed addresses on the table called addresses
Schema::create('addresses', function (Blueprint $table) {
$table->increments('id');
$table->integer('district_id')->unsigned();
$table->integer('thana_id')->unsigned();
$table->integer('area_id')->unsigned();
$table->integer('zip_id')->unsigned();
$table->integer('building_name_id')->nullable()->unsigned();
$table->string('building');
$table->integer('floor');
$table->string('apt')->nullable();
$table->text('comment')->nullable();
$table->timestamps();
$table->foreign('district_id')->references('id')->on('address_districts');
$table->foreign('thana_id')->references('id')->on('address_thanas');
$table->foreign('area_id')->references('id')->on('address_areas');
$table->foreign('zip_id')->references('id')->on('address_zips');
$table->foreign('building_name_id')->references('id')->on('address_building_names');
});
In Address Model I've defined relationships like:
public function district() {
return $this->belongsTo(AddressDistrict::class, 'district_id');
}
public function thana() {
return $this->belongsTo(AddressThana::class, 'thana_id');
}
public function area() {
return $this->belongsTo(AddressArea::class, 'area_id');
}
public function building_name() {
return $this->belongsTo(AddressBuildingName::class, 'building_name_id');
}
public function zip() {
return $this->belongsTo(AddressZip::class, 'zip_id', 'id');
}
Then when I try to create a new address using Address::create($data)
I get error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'name' in 'where clause' (SQL: select count(*) as aggregate from `address_zips` where `name` = 2)
Here we can see that it is comparing the key name instead of id
I noticed that this is not reporting that the data cannot be inserted or something like that, it fails to count related model & for that aborts insertion of data
Why is that?
But the strange thing is I can retrieve data by (inserted a row manually into db for testing to see if that can retrieve data)
$addresses = Address::orderByDesc('created_at')->get();
//loop as $address
$address->district->name
$address->zip->code
...
& this works perfect
When I am creating a new record I need that query look like:
select count(*) as aggregate from `address_zips` where `id` = 2
Any help will be highly appreciated.
Thanks for reading this long question.
The problem is in your $data array. Probably you copied a form with an input name, you need to rename it to code in order to save the values automatically.
Alternatively, you can set the input manually
$address = new Address();
$address->code = request('name');
$address->save();

Laravel Manual Update Timestamp

I have a miscellaneous database table that is updated each time a user visits another user's profile. I'm having trouble creating a manual timestamp column though. Since I didn't create a model for this, I'm doing it manually which shouldn't be an issue because this database isn't accepting any user-generated input.
Migration:
public function up()
{
Schema::create('recently_visited', function (Blueprint $table) {
$table->increments('id');
$table->integer('visitor_id');
$table->integer('profile_id');
$table->integer('times_visited');
$table->timestamp('last_visit');
});
}
Controller:
$visits = DB::table('recently_visited')
->where('profile_id',$user->id)
->where('visitor_id',Auth::user()->id)
->increment('times_visited')
->update(array('last_visit' => Carbon::now()));
I get the following error. Please help me understand, what is the integer this is being called on. Thanks!
Fatal error: Call to a member function update() on integer
ANSWER:
I just needed to include all my updated within the increment() in the query builder.
$visits = DB::table('recently_visited')
->where('profile_id',$user->id)
->where('visitor_id',Auth::user()->id)
->increment('times_visited', 1, ['last_visit' => Carbon::now()]);
Please help me understand, what is the integer this is being called on.
increment() method doesn't return query builder instance but rather updates the record itself and returns an integer.
You should be able to do this:
$visits = DB::table('recently_visited')
->where('profile_id',$user->id)
->where('visitor_id',Auth::user()->id)
->increment('times_visited', 1, array('last_visit' => Carbon::now()));

Resources