Laravel Return Migration and Eloquent Response - laravel

Is there any way to get the response or message from the migration and eloquent? Regardless of success or failure.
Migration:
$response = Artisan::call('make:model', [
'name' => 'MyModel'
'-m' => true
]);
//I need the response for my next step
Eloquent:
$response = MyModel::create($myValues);
//I need the response for my next step

Use like this:
$myModel = new myModel();
$myModel->value = 'value';
$myModel->save(); // you can use create or other function here
Now your result is in $myModel. It's not related to migration.

Related

How to manipulate a Laravel collection with related models and return a customized instance?

My model relation
return $this->hasMany('App\Models\Opportunity')->with('user');
My Attempt
$project = Project::find(1);
$$opportunities = $project->opportunities
->where('status', "confirmed");
$opportunities->each(function ($opportunity) {
return $opportunity->get('user');
});
Goal
My goal is to return the data in the following structure:
Opportunities:
Opportunity:
Status,
Amount
Currency
Name
Note that the user is a subset of the opportunity itself.
Problem
This returns a 1024 SQL error.
Ideally
It would be ideal if I can return all this information with the query itself.
Call get() method on your query to get its results first:
$oppurtunities = $project->opportunities()
->where('status', "confirmed")
->get();
You have eager loaded the user instance for each opportunity so just call $opportunity->user to return each opportunity's user:
$project = Project::find(1);
$opportunities = $project
->opportunities()
->where('status', "confirmed")
->get();
$filtered = $opportunities->map(function ($opportunity) {
return [
'status' => $opportunity->status,
'amount' => $opportunity->amount_pledged,
'currency' => $opportunity->currency,
'name' => optional($opportunity->user)->full_name
];
})->all();

How to queue the logics in controller

I have used two logic in my controller in my laravel project
public function multiStore()
{
$user = User::create([
'name'=>$request->name,
'email'=>$request->email,
'password'=>Hash::make($request->name),
]);
$post = MyPost::create([
'name'=>$request->post_name,
'body'=>$request->post_body,
]);
return redirect()->to('/admin/home);
}
Is it possible to make like if user is created successfully only then the post will be created so that I can use post created by user relationship
I have tried something like if condition but it is not working
You can try the code bellow , I assume you have a user_id field in posts table since you mentio9ned a relation ship. This is not the best way but i try to keep things simple, so I just edited the code.
Note : make sure you listed all the table fields in protected $fillable in your model before using Create()
public function multiStore()
{
$user = User::create([
'name'=>$request->name,
'email'=>$request->email,
'password'=>Hash::make($request->name),
]);
if($user){
$post = MyPost::create([
'user_id' => $user->id
'name'=>$request->post_name,
'body'=>$request->post_body,
]);
}
return redirect()->to('/admin/home);
}
Enclose your query in database transaction
https://laravel.com/docs/5.8/database#database-transactions
Either you can:
DB::transaction(function() {
Model::create();
AnotherModel::create();
});
Or you can use the following to find and catch error...
DB::beginTransaction();
// Your queries here...
// Model::create();
// AnotherModel::create();
DB::commit();

Query returning every row null in laravel

I'm trying to build a chat application using laravel echo and pusher, everything works but the data that returns to the databse is either null or the default value, here's the code
public function sendMessage(Request $request){
$conID = $request->conID;
$message1 = $request->message;
$user = Auth::user();
$fetch_userTo = DB::table('messages')
->where('conversation_id', $conID)
->where('user_to', '!=', Auth::user()->id)
->get();
$userTo = $fetch_userTo[0]->user_to;
$message = Message::create([
'user_from' => Auth::user()->id,
'user_to' => $userTo,
'conversation_id' => $conID,
'message' => $message1,
]);
if($message) {
$userMsg = DB::table('messages')
->join('users', 'users.id','messages.user_from')
->where('messages.conversation_id', $conID)->get();
broadcast(new MessagePosted($message))->toOthers();
return $userMsg;
}
}
NB: when i put insert() instead of create in the query the data goes through the database normally but there's an error in broadcasting
Have you tried to create a message like this? instead of using a model event?
$message = new Message;
$message->user_from = Auth::user()->id;
$message->$user_to = $userTo;
$message->conversation_id = $conID;
$message->message = $message1;
$message->save();
You have a lot more control this way, i.e
if($message->save()) { ... }
Or you could wrap the whole thing in a transaction?
Be sure your Message model allows the fields that you want to add in the $fillable array
Create method check fillable attributes into Laravel model. You have to write your all columns into fillable and then use create method.
Second solution is use Active Record technique. #Devin Greay answer is helpful to use Active record.
More information visit https://laravel.com/docs/5.6/eloquent#mass-assignment

UpdateExistingPivot for multiple ids

In order to update single record in pivot table I use updateExistingPivot method. However it takes $id as the first argument. For example:
$step->contacts()->updateExistingPivot($id, [
'completed' => true,
'run_at' => \Carbon\Carbon::now()->toDateTimeString()
]);
But how can I update multiple existing rows in pivot table at once?
There's an allRelatedIds() method in the BelongsToMany relation that you can access, which will return a Collection of the related model's ids that appear in the pivot table against the initial model.
Then a foreach will do the job:
$ids = $step->contacts()->allRelatedIds();
foreach ($ids as $id){
$step->contacts()->updateExistingPivot($id, ['completed' => true]);
}
You can update only by using a looping statement as there updateExistingPivot function only accept one dimensional params, See the core function for laravel 5.3.
File: yoursite\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Relations\BelongsToMany.php
Function: updateExistingPivot
public function updateExistingPivot($id, array $attributes, $touch = true)
{
if (in_array($this->updatedAt(), $this->pivotColumns)) {
$attributes = $this->setTimestampsOnAttach($attributes, true);
}
$updated = $this->newPivotStatementForId($id)->update($attributes);
if ($touch) {
$this->touchIfTouching();
}
return $updated;
}
So, You should follow the simple process:
$step = Step::find($stepId);
foreach(yourDataList as $youData){
$step->contacts()->updateExistingPivot($youData->contract_id, [
'completed' => true,
'run_at' => \Carbon\Carbon::now()->toDateTimeString()
]);
}

How to update column value in laravel

I have a page model. It has following columns in database table:
id
title
image
body
I want to update only "image" column value.
Here's my code:
public function delImage($path, $id) {
$page = Page::find($id);
$page->where('image', $path)->update(array('image' => 'asdasd'));
\File::delete($path);
}
it throws me an error, that i am trying to use where() on a non-object. How can i correctly update my "image" column value?
You may try this:
Page::where('id', $id)->update(array('image' => 'asdasd'));
There are other ways too but no need to use Page::find($id); in this case. But if you use find() then you may try it like this:
$page = Page::find($id);
// Make sure you've got the Page model
if($page) {
$page->image = 'imagepath';
$page->save();
}
Also you may use:
$page = Page::findOrFail($id);
So, it'll throw an exception if the model with that id was not found.
I tried to update a field with
$table->update(['field' => 'val']);
But it wasn't working, i had to modify my table Model to authorize this field to be edited : add 'field' in the array "protected $fillable"
Hope it will help someone :)
Version 1:
// Update data of question values with $data from formulay
$Q1 = Question::find($id);
$Q1->fill($data);
$Q1->push();
Version 2:
$Q1 = Question::find($id);
$Q1->field = 'YOUR TEXT OR VALUE';
$Q1->save();
In case of answered question you can use them:
$page = Page::find($id);
$page2update = $page->where('image', $path);
$page2update->image = 'IMGVALUE';
$page2update->save();
Try this method short and clean :
Page::where('id', $id)
->update(['image' => $path]);
An example from Laravel doc
Flight::where('active', 1)
->where('destination', 'San Diego')
->update(['delayed' => 1]);
DB::table('agents')
->where('id', $agentid)
->update(['status' => '0']);

Resources