Reputation: 1998
I've seen similar questions for other frameworks but I cant seem to find an answer for Laravel.
What is the best practise / cleanest solutions to achieve my goal.
At the moment lets say I have a model called Site
.
My site model has a column called prefix
which is just a few capital letters generated by the site name plus the new site id so for example, row 1 with a site name of 'clare' becomes 'CLA1' and 'pencet' becomes 'PEN2'.
My issue is that I need the new row id
to generate the prefix, which means at the moment I have to save it, then re-save it like so.
$site = new Sites;
$site->name = 'clare';
$site->save();
//Now that we have saved, we can use the new id to create the prefix and save again
$site->prefix = strtoupper(substr($site, 0, 3)) . $site->id;
$site->save();
I hate the fact I have to re-save it again once its initially been saved because I need the id, what is the best way to achieve this goal? Is it possible to return the new model ID before it saves?
I know I can do stuff like get a count of all of the rows and get the ID that way instead, but i'm generally looking for the best, cleanest solutions to achieve this.
Upvotes: 6
Views: 13880
Reputation: 11083
Try this solution :
Sites model :
public function getNextId()
{
$statement = DB::select("show table status like 'sites'");
return $statement[0]->Auto_increment;
}
Note: Do not forget to import DB with 'use Illuminate\Support\Facades\DB';
In the controller :
$site = new Sites;
$site->name = 'clare';
$site->prefix = strtoupper(substr($site->name, 0, 3)) . $site->getNextId();
$site->save();
Upvotes: 6
Reputation: 6646
I'm assuming some things in my answer, like the fact that you will never use the prefix to define a relationship or identify the site. This should always be done with the ID.
I would suggest using a property and a method in the Sites class to retrieve the prefix
:
private $generatedPrefix = null;
public function getPrefixAttribute() {
if ($this->generatedPrefix === null) {
$this->generatedPrefix = strtoupper(substr($this->site, 0, 3)) . $this->id;
return $this->generatedPrefix;
}
By doing it this way, you can access it by using the following code:
$site->prefix
The same logic as you want, but generated on the fly.
Upvotes: 0
Reputation: 574
How I do it is something like this ..
So I have a model
I define the
protected $fillable = []
array with the fields that can be mass filled.
Now I need a array with data and mass create :
$newRow = Page::create($data);
if($newRow) {
return Page::find($newRow->id);
} else {
return false;
}
So when the creation is success , I get the whole record back, otherwise false.
Of course this is implemented in a function within the model. So you need to call it from the controller or somewhere else :)
Upvotes: -1