eloquent get all row of a table and edit a field - laravel

I'm a newbie on laravel and I'm trying to use Eloquent to edit a field for all rows of a MySQL table.
So I create that:
<?php
namespace App\Http\Controllers;
use App\Mining;
use DB;
class FrontendController extends Controller{
public function cronDiff(){
$basic = GeneralSettings::first();
$row = Mining::all()->whereStatus(1)->get();
foreach ($row as $coins){
$code = Mining::where('coin_code', $coins->coin_code)->get();
$risultato = difficolta($code);
DB::table['minings']->insert('coin_code' => $code);
}
}
}
And I have a table minings like this:
id->int
name->varchar
coin_code->varchar
coin_diff->varchar
status->tinyint
But I can't update coin_diff using the value of $risultato (taken from other function)
Can you help to find out where I'm wrong?
Thanks.

try to use ->update('coin_code' => $code); instead ->insert
I think this solution would be better:
$minings = DB::table('minings')->get();
$minings->coin_code = $code;
$minings->update();

It should work like that: Mining::update(['coin_code' => $code]) if you have conditions you can chain them before update.
Also, you need to have the columns on models $fillable property. So, i don't know what error do you get but it might be from that.

If you want to update then why are you using insert?!
If you want to update a single row then modify your code
DB::table['minings']->insert('coin_code' => $code);
to
$coins->update(['coin_code' => $risultato]);
And make sure that $risultato have string value

Related

return table except deleted_at (softdeletes) laravel

I'm trying to return a table without deleted rows (softdeletes)
This is my code
public function getMailRecipients($meoId){
return DB::table('mail_recipients')->where('meo_id', '=', $meoId)->select('name', 'email')->get();
}
but I get all rows, even those removed through softdeletes, What else should I add to avoid that?
thanks!
you are using query builder (facade DB) in this case you should do this:
DB::table('mail_recipients')->where('meo_id', '=', $ meoId)->whereNull('deleted_at')->select('name', 'email')->get();
If you use the model, you must use the SoftDeletes trait
class Flight extends Model{
use SoftDeletes;
}
see more in the documentation
https://laravel.com/docs/8.x/eloquent#soft-deleting
Note *: The soft deleting feature works when using Eloquent. If you are querying the results with query builder you will eventually see all the records trashed and not trashed.
You can try with this:
public function getMailRecipients($meoId)
{
return DB::table('mail_recipients')
->whereNull('deleted_at')
->where('meo_id', $meoId)
->get(['name', 'email']);
}
If you arrived here because you are using protected $softDelete = true in your model and Laravel seems to ignore it, the solution is to use Illuminate\Database\Eloquent\SoftDeletes in your model. Works everytime!

How to use Model in function parameter to reduce code in laravel?

This is how i am trying to update record in my laravel function which doesn't work
public function completePacking(SaleOrder $saleOrder)
{
$saleOrder->update(['status' => 'Draft']);
}
it is working
public function completePacking($id)
{
$saleOrder = SaleOrder::findOrFail($id);
$saleOrder->status = 'Dispatched';
$saleOrder->save();
}
i want to use first method because it is less code but that is not working
Add 'status' to your $fillable attribute in your SaleOrder model.
Or remove 'status' from $guarded attribute in SaleOrder model.
After doing any of the following, you would be able to use your desired version to update status.
Read more on https://laravel.com/docs/5.7/eloquent#mass-assignment
$saleOrder = SaleOrder::where('id', $id)->update(['status' => 'Draft']);

How to use orderBy() with model's method in Laravel

How can I use orderBy to order by a model's method?
Consider the model User and the method
public function fullName() {
return $this->firstName . $this->lastName;
}
I want to do something like orderBy('fullName'). Is this possible? I know I can make equivalent code using Query Builder, but I want to keep my Model methods as they are.
I think you have a few options here:
Create a view in your database, which has the column fullName. Then change your model to use the view.
Create a computed column fullName so that on insert if will use the values given from firstName and lastName.
Use Laravel's Collection class. This class provides a sortBy method which you can use an attributes.
If you go with option 2, first define an attribute:
public function getFullNameAttribute()
{
return $this->firstName . $this->lastName;
}
Then using Laravel's Collection:
$items = Model::all()->sortBy('FullName');
Note: The default option for sortBy is ascending, so if you wish to sort descending:
$items = Model::all()->sortByDesc('FullName');
You can read more about accessors here: https://laravel.com/docs/5.7/eloquent-mutators#defining-an-accessor
I've solved the problem with this solution:
$sorted = User::get()
->sortBy('full_name') //appended attribute
->pluck('id')
->toArray();
$orderedIds = implode(',', $sorted);
$result = DB::table('user')
->orderByRaw(\DB::raw("FIELD(id, ".$orderedIds." )"))
->paginate(10);
I've appended fullName attribute to the model, to be used by sortBy.
With this solution I was able to use orderBy to order by an appended attribute of the model, exactly what I wanted to do. So yes, it is possible. And also I was able to use pagination. Thanks to all who tried to help.
$personas = Persona::select('*');
$personas = $personas->addSelect(DB::raw('concat(nombre,\' \',apellido1,\' \',apellido2) as fullname'))
->orderBy('fullname', 'ASC')->paginate(K_LINEAS_X_PAGINA);
I couldn't make it work without the select('*')

Laravel 5.4 elequent create method generate wrong query

I am trying to insert data in a table using eloquent create method, But data which I have passed not coming in insert query generated by create method. Due to which I am getting a default value error.
Below are the code i have used
Model :
namespace App;
use Illuminate\Database\Eloquent\Model;
class PasswordReset extends Model
{
protected $fillable = ['email', 'token'];
}
Controller :
$content = ['email'=>'test#gmail.com', 'token'=>'1234'];
PasswordReset::create($content);
Error I am getting :
SQLSTATE[HY000]: General error: 1364 Field 'email' doesn't have a default value (SQL: insert into password_resets (updated_at, created_at) values (2018-09-25 16:16:45, 2018-09-25 16:16:45))
Why query in above error does not have 'email' and 'token' fields?
from your comment:
#cbaconnier, Thanks, After looking your comment. I have checked with my code and its having a __construct method without having any code within it and removing this resolve the issue.
If you want to use __construct() on the Model, you need to build it like this
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
// your code
}
I think you should create like this
PasswordReset::create([
'email'=>'test#gmail.com',
'token' => '1234'
]);
try this way :
$passwordReset = new PasswordReset();
$passwordReset->email = 'test#gmail.com';
$passwordReset->token = '12345';
$passwordReset->save();
try this i hope work for you :
PasswordReset::create([
'email'=>'test#gmail.com',
'token' => '1234']);

Inserting a variable in sql through laravel

I am trying to insert data into sql in laravel 5
My Code:
$a1=Input::get('username');
$a2=Input::get('reg_no');
DB::insert("INSERT INTO ngosignup VALUES($a1,$a2)");
But I am getting SQL error:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an
error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near
'#gmial.com,a,a,a,a,9,a,9814937684,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,N'
at line 1 (SQL: INSERT INTO
ngosignup(name,email,pass,confirmpass,address,city,pin,state,mobile,registration,secretary,dest,firstmember,mobile1,secondmember,mobile2,thirdmember,mobile3,objective,dev1,place1,obj1,dev2,place2,obj2,dev3,place3,obj3)
VALUES(a,amit#gmial.com,a,a,a,a,9,a,9814937684,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL))
PLEASE HELP.
Try Eloquent way.. for example of using your db.. Make a Model for ngosignup table and include it on controller
public function create(\Illuminate\Http\Request $request) {
$input = $this->request->all();
$a1 = $input['username'];
$a2 = $input['reg_no'];
$newngo = new ngosignup; //Replace ngosignup with your Model name.
$newngo->name = $a1; //name and reg_no should be column name
$newngo->reg_no = $a2;
$newngo->save(); //this will add these values into your DB
}
You can do this way.. Easier and Flexible.. You can add validator.. Refer to Laravel docs on their official site :)
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\ngosignup;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class ngosignupController extends Controller
{
public function index() {
$ngo = ngosignup::first(); // this shows first row of table..you can use get() instead of first to get all table as collection.
$data= array(
'ngo ' => $ngo
);
return View('index', $data);
}
Then on Index.Blade.php File.. you can display data from ngosignup table like
{{ $ngo->email }} // replace email with which data to display. if ollection.. use foreach loop to display all data.
Refer to Laravel docs.. they list all methods available..

Resources