insert data to a migration without a model - laravel

How to insert data to a migration (table) without a model in Laravel, a migration with its model in which I define the corresponding relationships and the other only the migration
It can clearly be done according to the documentation of Laravel when you have the migration with your respective model, as follows.
$comment = new App\Comment(['message' => 'A new comment.']);
$post = App\Post::find(1);
$post->comments()->save($comment);
or
$post = App\Post::find(1);
$comment = $post->comments()->create([
'message' => 'A new comment.',
]);
This works for me only when I have with their respective models but not as I want to do
I am pending if someone can clarify with this

You can interact with database directly without a model using the DB facade:
DB::table('tablename')->insert(['column'=>'value']);
Same way you can use wheres, selects. For more details see Laravel docs - Database: Query Builder - Inserts

Related

Loading relation of new model in Laravel

I just want to get hasOne relation of New model.
Can I load it before I will save it.
I have $user = new User(['order_id' => $order_id]);
How can I get $user->order; without build new request?
As others have already pointed out the model must be saved before retrieving any relations.
My usual approach for this is using lazy eager loading:
// Create new model with data
$newModel = Model::create([
'column' => $value
]);
// Use load to retrieve any relations
return $newModel->load('myRelationship');

Laravel 8.0 facing issue while trying to update a table with vue form, 'Attempt to read property \"item_id\" on null'

So, i have a table called Items table and another table called item_quantities, on item_quantities ive a column named item_id which is connected to items table id. All the fillable properties on both tables are all in one form on the frontend, and i take care of the form fields on the backend
Whenever i try to update the quantity on the form which is from item_quantities's table with a form, i'm facing serious issue updating the item_quantities. getting Attempt to read property "item_id" on null.
It all started when i noticed a duplicate entries on the item-quantities table, so i deleted all the datas on it..
Here's is the form screenshot
The vue form
and the backend logic
public function saveData(Request $request, $id) {
// dd($request->name);
$updateGroceries = Item::where('id', $request->id)->get()->first();
$updateGroceries->update([
'name' => $request->name,
'description' => $request->description,
'price' => $request->price,
]);
if($updateGroceries) {
$item_quantity = ItemQuantity::where('item_id', $updateGroceries->id) ?
ItemQuantity::where('item_id', $updateGroceries->id)->get()->first() :
new ItemQuantity;
if($item_quantity->item_id == null) {
$item_quantity->item_id = $updateGroceries->id;
}
$item_quantity->quantity = $request->quantity;
$item_quantity->save();
}
}
I'M SO SORRY IF MY ENGLISH WAS'NT CLEARED ENOUGH
Thanks in anticipation
You can simply use firstOrNew() method. This will first find the item, if not exist create e new instance.
$item_quantity = ItemQuantity::firstOrNew(['item_id' => $updateGroceries->id]);
$item_quantity->quantity = $request->quantity;
$item_quantity->save();
Note that the model returned by firstOrNew() has not yet been persisted to the database. You will need to manually call the save method to persist it.
Actually your errors workflow as that:
$item_quantity=null;
$item_quantity->item_id;
You can do that with optional global helper:
optional($item_quantity)->item_id ?: 'default value';

User::all show relationship items

I Laravel 5.5 I am returning users information like this...
$users = User::all();
return Response::json(array(
'error' => false,
'response' => $users,
));
I have a belongs to many categories relationship setup and would like to also show all of the categories each user belongs to.
Anyone have an example I can see?
Use the with() method to load categories for each user:
$users = User::with('categories')->get();
If you don't need to load all the columns from the categories table, use select() inside the with() closure. Also, since you're using Laravel 5.5 you could use Resource classes for formatting JSON.

Laravel 5 : Couldn't instancing a model using tinker

I'm very new to laravel and PHP MVC frameworks, it's my first use of Eloquent. I'm trying to following a video tutorial.
So after creating a table by making new migration and migrate with artisan.
I created a model.Then I tried to instance it using tinker tool like so :
>>> $task = new App\Task;
I got this error :
=> App\Task {#672}
this my model class :
class Task extends Model
{
protected $table = 'tasks';
}
I did many research before asking this question, some people recommends using homestead, but I want to understand what I'm doing wrong.
This is not an error. It shows that an Object of App\Task Class has been created.
Now you can assign values to this $task Object. Like we have a field 'name' in tasks table then the following part of code can save the $task in database with value of 'name' field.
$task = new App\Task;
$task->name = 'My first task';
$task->save();

Can you create a new Model instance without saving it to the database

I want to create a whole bunch of instances of a model object in Laravel, then pick the optimal instance and save it to the database. I know that I can create an instance with Model::create([]), but that saves to the database. If possible I'd like to create a bunch of models, then only "create" the one that is best.
Is this possible?
I am using Laravel 5.0
You create a new model simply by instantiating it:
$model = new Model;
You can then save it to the database at a later stage:
$model->save();
You can create instances with Model::make(). It works the same way as create but it doesn't save it.
Whether or not this is best practice is another matter entirely.
Yes, it is possible different ways: you can use the mass assignment without saving.
Please remember to set first the $fillable property in your model.
WAY #1: using the method fill
$model = new YourModel;
$model->fill([
'field' => 'value',
'another_field' => 'another_value'
]);
$model->save();
WAY #2: using the constructor
$model = new YourModel([
'field' => 'value',
'another_field' => 'another_value'
]);
$model->save();
In YourModel set the $fillable property with the fileds allowed for mass assignment:
class YourModel extends Model
{
protected $fillable = ['field', 'another_field'];
// ...
}
Laravel documentation: https://laravel.com/docs/9.x/eloquent#mass-assignment
there is also a method you can call it statically to get new instance:
$modelInstance = $modelName::newModelInstance();
it takes array $attributes = [] as a parameter

Resources