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();
Related
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.
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'm trying to connect users table with user_info. I've found some posts about it and it works, but I've troubles with user_info->id autoincrement.
If I set it to:
$table->increments('id');
I'm getting error that no default value is set, it works only if I add
$table->integer('id')->nullable($value = true);
Here is what I got for now:
User model
public function userinfo()
{
return $this->hasOne('App\Userinfo');
}
Userinfo model
public function user()
{
return $this->belongsTo('App\User');
}
Migration/table structure
public function up()
{
Schema::create('user_info', function (Blueprint $table) {
//There is a problem, if I don't add user_id it says that user_id doesnt exists, so I created user_id and decided to set id to autoincrement but it doesnt works so I made it like that
$table->integer('id')->nullable($value = true);
$table->foreign('id')->references('id')->on('users');
$table->integer('user_id');
$table->string('avatar',255)->default('notset.jpg')->nullable($value = true);
$table->string('looking_for',255)->nullable($value = true);
$table->string('steam_nick',40)->nullable($value = true);
$table->integer('age')->length(3)->nullable($value = true);
$table->integer('isFriendly')->length(2)->nullable($value = true);
$table->integer('isToxic')->length(2)->nullable($value = true);
$table->integer('isLeader')->length(2)->nullable($value = true);
$table->integer('isFunny')->length(2)->nullable($value = true);
$table->integer('isSkilled')->length(2)->nullable($value = true);
$table->text('description')->nullable($value = true);
$table->timestamps();
});
}
Finally UserinfoController
public function update(Request $request, $id)
{
$user = User::findOrFail($id); //Get role specified by id
$this->validate($request, [
'steam_nick'=>'max:120',
'looking_for'=>'required',
'avatar'=>'',
'description'=>'max:450',
'age'=>'min:2'
]);
$input = $request->only(['steam_nick', 'looking_for', 'description','avatar','age']); //Retreive the name, email and password fields
$userinfo = new Userinfo();
if ($userinfo->user_id == null ) {
$userinfo->steam_nick = $request->steam_nick;
$userinfo->looking_for = $request->looking_for;
$userinfo->description = $request->description;
$userinfo->avatar = $request->avatar;
$userinfo->age = $request->age;
$user->Userinfo()->save($userinfo);
} else {
$user->Userinfo()->update($input);
}
}
Phpmyadmin
img
All I need is to set id in user_info same as id in users. I don't need user_id, but couldn't make it works other way, but I'm sure it's wrong.
Okay, let's break it down piece by piece.
First, what I like to do is specifically declare what my table column is as the second argument on any hasOne and belongsTo in a model. It's not strictly necessary since Laravel does some voodoo magic to guess what the table name is - but I recommend it because it makes the relationship very clear. So, I would do this on the user model:
public function userinfo()
{
return $this->hasOne('App\Userinfo', 'user_id'); // it references user_id on your user_info table.
}
Next, let's look at your user_info migration. You were having problems with your primary key id because you were trying to set it as integer when it needs to be increments. We'll tweak the first three lines:
$table->increments('id')->unsigned();
$table->integer('user_id');
$table->foreign('user_id')->references('id')->on('users'); // foreign references the user_id field in this table, since that's what's making the connection between users and users_info, we point back to the user's id
At this point, if you are able, I recommend php artisan migrate:fresh --seed. It might help with any weird database structures you have prior. This is optional, though. You can try it if it doesn't work straight away.
Now in the controller, I noticed that you were previously referencing $user->Userinfo()->update($input);, but you named the relationship userinfo() in your user model. This is probably one of the things that was giving you an issue. They must match. Try setting up your controller like so:
public function update(Request $request, $id)
{
$user = User::findOrFail($id); //Get role specified by id
$this->validate($request, [
'steam_nick'=>'max:120',
'looking_for'=>'required',
'avatar'=>'',
'description'=>'max:450',
'age'=>'min:2'
]);
$input = $request->only(['steam_nick', 'looking_for', 'description','avatar','age']); //Retreive the name, email and password fields
// Does this user have an info record? If not, create it, else update it.
if (is_null($user->userinfo)) {
// Since you already collected the data in the $input variable, we simply array_merge it with the user's id
Userinfo::create(array_merge([
'user_id' => $user->id,
], $input));
} else {
$user->userinfo()->update($input);
}
return redirect()->back();
}
So, basically what we are doing is checking to see if the user has a related record in the user_info table. If not, create it with the data. If so, simply update it. Since in our migration we declare that user_id cannot be null, we have to grab the user's id off the $user variable, and you've already grabbed all of the necessary data for the user_info table and put it in the $input variable, we simply array_merge() those two arrays when creating the user's info record.
Otherwise, if the related record already exists, we simply update the user_info record using our relationship ->userinfo().
Try that and let me know how it works.
I'm trying to edit a column of datatable to show informations in my index view table.
This is my controller's method that I call throught Ajax in the view:
public function getField(){
// Current User
$user_id = \Auth::user()->id;
$users = User::find($user_id)->users();
return Datatables::of($users )
->editColumn('id', 'Edit')
->editColumn('fields_id', function($users) {
$mystring = '';
$fields_id_array = json_decode($users->fields_id);
foreach($fields_id_array as $f_id){
/* this works */
// $mystring .= Fields::where('id', '=', $f_id) -> pluck('field_name');
/* this doesn't work */
$mystring .= Fields::find($f_id) -> pluck('field_name');
}
return $mystring;
})
->rawColumns(['id'])
->make(true);
}
The field 'fields_id' in users table is a JSON field like this: ['1','2','5'] and these refers to the id's of another table: 'Fields'.
I have already read this questions but I think my db table is it ok because increments are primary-key equivalent in Laravel migrations.
This is my migration for the table 'fields':
public function up()
{
Schema::defaultStringLength(191);
Schema::create('fields', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->string('code')->unique();
$table->string('param1');
$table->string('param3')->nullable();
$table->timestamps();
});
}
Thanks
a wild guess here, based on your last comment...
try this inside you loop
$mystring .= Fields::find(intval($f_id))->pluck('field_name');
I've added the intval() function arround your $f_id since you said you said they are in this format ['1','2','5']. that is an array of strings (that should be cast to integers if you plan to use them with find() function.
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();