sending model to view along id after save() in laravel - php

In my controller I am defining a model and persisting it to the DB with save() :
$model = new Model();
$model->attrib = "something";
$model->save();
Ok so now I want to send this newly created data to my view like this:
return view('new_model', ['new_model' => $model]);
The problem is the data passes to the view but not the id assigned to the model in the DB.
How can I possibly send this data without performing a new query to the DB after the save();
Shouldn't the $model->save(); save to the DB and return what it persisted in the DB along id and all the stuff?
I stand corrected, the id was appearing at the end of the data.

$model->id should be the last id inserted.

Eloquent allows you to fill models by passing an associative array with values, and the keys representing the column names.
$model = Model::create([
'attrib' => 'something',
]);
You will get the id by $model->id.
Hope it works. :)

Related

i have problem with save data laravel 8 have

i make this query
public function scopeSelection($query){
return $query -> select('abbr', 'name', 'direction', 'active');
}
and this function for save data but nothing save in my database
public function store(LanguageRequest $request)
{
try {
Language::created($request->except(['_token']));
return redirect()->route('admin.languages')->with(['success' => 'success']);
} catch (\Exception $ex) {
return redirect()->route('admin.languages')->with(['error' => 'error']);
}
}
To insert a new record into the database, you should instantiate a new model instance and set attributes on the model. Then, call the save method on the model instance:
$language = new Language();
$language->iso = $request->iso;
$language->save();
In this example, we assign the iso field from the incoming HTTP request to the iso attribute of the App\Models\Language model instance. When we call the save method, a record will be inserted into the database. The model's created_at and updated_at timestamps will automatically be set when the save method is called, so there is no need to set them manually.
Alternatively, you may use the create method (not created) to "save" a new model using a single PHP statement. The inserted model instance will be returned to you by the create method:
use App\Models\Language;
$language= Language::create([
'iso' => 'enGB',
]);
However, before using the create method, you will need to specify either a fillable or guarded property on your model class. These properties are required because all Eloquent models are protected against mass assignment vulnerabilities by default. To learn more about mass assignment, please consult the mass assignment documentation.

Saving two models to sync into pivot table

I have a request controller that has two Model to be save for me able to sync this into my pivot table. I still don't have idea how I'm gonna sync one of the two Models in my Controller. I have Documents and Approves M:M relationship with a pivot table approve_document
Model
Document:
public function approves()
{
return $this->belongsToMany('App\Models\Document', 'approve_document');
}
Approve:
public function pendingDocuments()
{
return $this->belongsToMany('App\Models\Document', 'approve_document');
}
Controller:
$document = new Document();
$approve = new Approve();
//Request in the form
$document->title = $request->title;
$document->content = $request->content;
$document->category_id = $request->category;
$approve->approver_id = $request->approver;
$approve->save();
$document->save();
$document->approves()->sync([$approve],false);
Honestly here I still don't have idea what should I put inside my sync array. It throws me a error Illegal offset type. Any help to correct my error?
Update
sync() Method accepts the ids of the Models to be attached.
So, in your case sync() method will need id of the approve model.
$document->approves()->sync([$approve->id],false);
//assuming id is the PK for your Approve model
Reference: Inserting Related Models

Store all values (received by form) in database except 2 for modification in laravel

I am new in Laravel, i am trying to send all the values of a form to a database along with some other/modified values by using fill() in laravel 5.1.
here is how my controller looks like
public function store(Request $request)
{
$pages = new Pages; //i have a model with name Pages
$pages->fill(Input::all());
$pages->save();
return "data saved successfully";
}
Whenever i want to fill data into the table i get these values.
But before sending the data into database i want to mention some other attributes as well like $userid, change the datetime format to timestamp and then i want to send the data to database.
I want to use fill(Input::all()); method because if i need to add more field in the form, then i wont have to modify my controller or model.
Any suggestion will be helpful.Or any other best practice will also work.
Thank you! (in advance)
You can use eloquent
public function store(Request $request)
{
$request['user_id']='your id';
Pages::create($request->all());
return "data saved successfully";
}
If not eloquent
try this
$pages = new Pages; //i have a model with name Pages
$request['user_id']='your id';
$pages->fill(Input::all());
$pages->save();
return "data saved successfully";

How to get last insert id in Eloquent ORM laravel

I am performing a database operation with "Eloquent ORM in Laravel". I just want to take the last insert id (not the maximum id) in the database.
I searched to get last insert id in laravel Eloquent ORM, I got following link (Laravel, get last insert id using Eloquent) that is refer to get last insert id from following function "$data->save()".
But I need to get
"Model::create($data)";
My Query:
GeneralSettingModel::create($GeneralData);
User::create($loginuserdata);
How can I retrieve the last inserted id?
Like the docs say: Insert, update, delete
"You may also use the create method to save a new model in a single
line. The inserted model instance will be returned to you from the
method. However, before doing so, you will need to specify either a
fillable or guarded attribute on the model, as all Eloquent models
protect against mass-assignment.
After saving or creating a new model that uses auto-incrementing IDs,
you may retrieve the ID by accessing the object's id attribute:"
$insertedId = $user->id;
So in your sample:
$user = User::create($loginuserdata);
$insertedId = $user->id;
then on table2 it is going to be
$input['table2_id'] = $insertedId;
table2::create($input);
**** For Laravel ****
$user = new User();
$user->name = 'John';
$user->save();
//Getting Last inserted id
$insertedId = $user->id;
You could wrap your data in the insertGetId() method like this
$id = DB::table('table')->insertGetId( $data );
In this case the array $data would look something like this
$data = [ 'field' => 'data' , 'field' => 'data' ];
and if you’re using the DB façade you could just append the lastInsertID() method to your query.
$lastInsertedID = DB::table('table')->insert( $data )->lastInsertId();
$lastId = User::create($loginuserdata)->id;
As others said bfore me you may retrieve id by using
$model->id;
but only if you are using standard naming convention for eloquent. If you want to use other name for primaryKey column, eg:
class Users extends Model{
$primaryKey = 'userid';
}
you may retrieve last inserted id by calling
$model->userid;
It is described in: https://laravel.com/docs/master/eloquent#eloquent-model-conventions where one can find:
Eloquent will also assume that each table has a primary key column
named id. You may define a $primaryKey property to override this
convention.
In addition, Eloquent assumes that the primary key is an incrementing
integer value, which means that by default the primary key will be
cast to an int automatically. If you wish to use a non-incrementing or
a non-numeric primary key you must set the public $incrementing
property on your model to false.
You may do it as,
public function store(Request $request,ModelName $obj)
{
$lastInsertedId = $obj->create($request->all())->id;
}
Hope this will help you.
This is my try:
$model_ins = Model::orderBy('id', 'desc')->take(1)->first();
And use $model_ins->id.
This code works with Laravel 5.3:
$upstatus = User::create($status);
return response()->json($upstatus);
User pages/site I was call data.id
This is an eloquent model:
$user = new Reports();
$user->email= 'david#example.com';
$user->save();
$lastInsertId = $user->id;
A solution using Query Builder:
$lastInsertId = DB::table('reports')->insertGetId(['email' => 'david#example.com']);
$user = (new user)->create($request->all()) ;
\Session::flash('message', 'Thanks , Your record No (' .$user->id . ') has been Successfully added');
This is my solution. I return the inserted object and get its ID or any other property.
This is an easier way that works on all of the ways that you inserted:
DB::getPdo()->lastInsertId()

Find or Create with Eloquent

I have recently started working with Laravel and Eloquent, and was wondering about the lack of a find or create option for models. You could always write, for example:
$user = User::find($id);
if (!$user) {
$user = new User;
}
However, is there not a better way to find or create? It seems trivial in the example, but for more complex situations it would be really helpfully to either get an existing record and update it or create a new one.
Below is the original accepted answer for: Laravel-4
There is already a method findOrFail available in Laravel and when this method is used it throws ModelNotFoundException on fail but in your case you can do it by creating a method in your model, for example, if you have a User model then you just put this function in the model
// Put this in any model and use
// Modelname::findOrCreate($id);
public static function findOrCreate($id)
{
$obj = static::find($id);
return $obj ?: new static;
}
From your controller, you can use
$user = User::findOrCreate(5);
$user->first_name = 'John';
$user->last_name = 'Doe';
$user->save();
If a user with id of 5 exists, then it'll be updated, otherwise a new user will be created but the id will be last_user_id + 1 (auto incremented).
This is another way to do the same thing:
public function scopeFindOrCreate($query, $id)
{
$obj = $query->find($id);
return $obj ?: new static;
}
Instead of creating a static method, you can use a scope in the Model, so the method in the Model will be scopeMethodName and call Model::methodName(), same as you did in the static method, for example
$user = User::findOrCreate(5);
Update:
The firstOrCreate is available in Laravel 5x, the answer is too old and it was given for Laravel-4.0 in 2013.
In Laravel 5.3, the firstOrCreate method has the following declaration:
public function firstOrCreate(array $attributes, array $values = [])
Which means you can use it like this:
User::firstOrCreate(['email' => $email], ['name' => $name]);
User's existence will be only checked via email, but when created, the new record will save both email and name.
API Docs
Alternatively, in this case you can also use Laravel's function and search for id as an attribute, i.e.
$user = User::firstOrCreate(['id' => $id]);
Find or New based on primary key id
$user = User::findOrNew($id); // if exist then update else insert
$user->name= $data['full_name'];
$user->save();
First or New based on non-primary key single filed
// get the record where field_name=value else insert new record
$user = User::firstOrNew(['field_name'=>'value']);
$user->name= $data['full_name'];
$user->save();
First or New based on non-primary key multiple filed
// get the record where field_name1=value1 and field_name2=value2, else insert new record
$user = User::firstOrNew(['field_name1'=>'value1','field_name2'=>'value2']);
$user->name= $data['full_name'];
$user->save();
In Laravel 5:
There are two methods you may use to create models by mass assigning attributes: firstOrCreate and firstOrNew.
The firstOrCreate method will attempt to locate a database record using the given column / value pairs. If the model can not be found in the database, a record will be inserted with the given attributes.
The firstOrNew method, like firstOrCreate will attempt to locate a record in the database matching the given attributes. However, if a model is not found, a new model instance will be returned. Note that the model returned by firstOrNew has not yet been persisted to the database. You will need to call save manually to persist it:
// Retrieve the flight by the attributes, or create it if it doesn't exist...
$flight = App\Flight::firstOrCreate(['name' => 'Flight 10']);
// Retrieve the flight by the attributes, or instantiate a new instance...
$flight = App\Flight::firstOrNew(['name' => 'Flight 10']);
Laravel 4 models have a built-in findOrNew method that does what you need:
$user = User::findOrNew($id);
You can use firstOrCreate (It's working with Laravel 4.2)
$bucketUser = BucketUser::firstOrCreate([
'bucket_id' => '1',
'user_id' => '2',
]);
returns found instance or new instance.

Categories