how to print model query in laravel - laravel

i am new in laravel and have to save the record in table , i am using this code to insert the value
$model->studentRollId = $value1;
$model->resident_permit_number = $value2;
$model->save()
i am not getting any error but record not inserting in the table , so can anyone please tell me how can i print the executed query by the $model->save(), i tried DB::getQueryLog() but its not shiwing the query log so i can fin what is the issue . thanks in advance

Use ->toSql(), after your $model->save(), just do a dd($model->toSql())
Edit: Have you do a \DB::enableQueryLog();?
\DB::enableQueryLog();
$model->studentRollId = $value1;
$model->resident_permit_number = $value2;
$model->save()
dd(\DB::getQueryLog());

Try This
$model->studentRollId = $value1;
$model->resident_permit_number = $value2;
$data = $model->toSql();
dd($data);

Do you have studentRollId and resident_permit_number in the $fillable array?
Go to the $model and check if you have something like this:
protected $fillable = [
'studentRollId',
'resident_permit_number'
];
Another solution would be to insert data in raw like this:
DB::table('table_name')->insert([
'studentRollId' => $value1,
'resident_permit_number' => $value2
]);
Hope it helps.

Have you mentioned the column names in $fillable in you model. In laravel to insert a data in table you have to mentioned the columns names in $fillable method.
e.g.
Suppose you have users table and for that table you have User model.
In User.php add following method
protected $fillable = [
'list of columns'
];

Related

How to get currently inserted row id in laravel 5.5

Here I am using laravel 5.5. My code is
$result = DB::insert('INSERT INTO .......');
Here it returns true. But how can I get inserted id? In my table id is the primary key. Thanks in advance
you can use insertGetId().
If the table has an auto-incrementing id, use the insertGetId method to insert a record and then retrieve the ID:
$id = DB::table('users')->insertGetId(
['email' => 'john#example.com', 'votes' => 0]
);
doc can be found here.
Instead of using DB method you can simply use Laravel eloquent:
$result = <YOUR_MODEL_NAME>::create(<YOUR_DATA>)->id();
it return the last inserted record id.
And make sure if you use this method you need to add $fillable in your MODEL like:
class <YOUR_MODEL> extends Model
{
protected $fillable = [ 'column_name_1', 'column_name_2', .., 'column_name_n' ];
}
Why don't you order your rows and get last id?
select <primary key> from <table> order by desc limit 1;
$result = MODEL_NAME::create(data);
return $result->id;
try this may be it's working

Get formatted date at Eloquent results

Considering that the model is
class Cota extends Model
{
protected $fillable = ['status','user_id','produto_id','numero','arquivo','updated_at'];
protected $dates = [
'updated_at',
];
//protected $dateFormat = 'd/m/Y';
}
And considering the query:
$cotas = DB::table('cotas')->join('produtos','produtos.id','=','cotas.produto_id')->join('users','users.id','=','cotas.user_id')->select('cotas.id','produtos.titulo as produto','cotas.numero','cotas.arquivo','users.name','cotas.status','cotas.updated_at','produtos.valor')->get();
When I get only one instance, like:
$cota = Cota::find(6517);
I can do this:
$cota->updated_at->format('d/m/Y');
But in the query above, the results come always with the traditionl date format used by Mysql.
How do I get the results with the ('d/m/Y') format? I have to use a raw query? Is that the only way?
Thanks!
You can always user DB::raw in Select statement.
$cotas = DB::table('cotas')
->join('produtos','produtos.id','=','cotas.produto_id')
->join('users','users.id','=','cotas.user_id')
->select([
'cotas.id',
'produtos.titulo as produto',
'cotas.numero',
'cotas.arquivo',
'users.name',
'cotas.status',
DB::raw('DATE_FORMAT(cotas.updated_at, "%d/%m/%Y"') as updated_at,
'produtos.valor'
])
->get();
// Or Else You can always loop over your collection when displaying data / using that data.
You can use date casting like so
protected $casts = [
'updated_at' => 'datetime:d/m/Y',
];
This is only useful when the model is serialized to an array or JSON according to the docs.

How do I "json_decode" a single column data after fetch from database in Laravel?

I am saving an array in one column of my database using json_encode as follows and it works:
$service->description = $request->service_description;
$service->image = json_encode($url);
$service->duration = $request->service_delivery_time;
When I fetch the data I get a string. I am fetching using $service = Service::findOrFail($id);. I can decode the individual column as done below and pass it to the view.
$service = Service::findOrFail($id);
$images = json_decode($service->image);
return view('services.show',['service'=>$service , 'images'=>$images]);
What I am asking is, can I decode the images in one query?
Well this is a single query, json_decode runs after the SQL query returned your desired result.
What you can do is add a $casts property to your Service model so Laravel encodes/decodes it automatically for you, then you don't need to store these values with json_encode, just do $service->image = $url, and when you run findOrFail, the image property will already be a decoded json.
protected $casts = [
'image' => 'array',
];
Here's the documentation
You can use $cast or Accessor
1: $cast:
protected $casts = [
'image' => 'array'];
2: Accessor:
public function getImageAttribute()
{
return json_decode($this->attributes['image']);
}

Laravel insert into database request()->all() and addition

In laravel if i want to insert all the form input and i want to add text in one of the column why cant i use this code?
Example
$B2 = new B2;
$B2::create([
request()->all(),
$B2->column9 = "aaaa",
]);
The inserted database only insert column9, the other column is Null.
Because create() accepts an array as the only parameter:
public static function create(array $attributes = [])
You can do this:
$data = request()->all();
$data['column9'] = 'aaaa';
B2::create($data);
When ever you use request all you must first make sure that you have either fillable fields in your model or guarded = to an empty array so for example:
class B2 extends Model
{
protected $table = 'db_table';
protected $fillable = [
'email',
'name',
];
}
or you can use
protected $guarded = [];
// PLEASE BE CAREFUL WHEN USING GUARDED AS A POSE TO FILLABLE AS IT OPENS YOU TO SECURITY ISSUES AND SHOULD ONLY REALLY BE USED IN TEST ENVIRONMENTS UNLESS YOU REALLY KNOW WHAT YOU ARE DOING!
As for your create method you should make sure its an associative array like this:
$B2::create([
$B2->column9 => "aaaa",
]);
Or you could do something like:
$data = $request->except('_token');
$B2::create($data);
You'll have to merge the array.
$B2::create(array_merge(request()->all(), ['column9' => 'text']));
When you are adding to a database in that was it is called mass assignment. Laravel Automatically protects against this so you need to add the firld names to a fillable attribute in your model
protected $fillable = ['field1', 'column9'] //etc
https://laravel.com/docs/5.4/eloquent#mass-assignment
You also need to make sure you pass an array to the create method
$my_array = $request->all()
$my_array['column9'] = 'aaaa';
$B2::create(
$my_array
);

Laravel Column Manually Added Cannot be Updated

So I have been searching but I couldn't find the correct answer to this.
I have an existing User table and added a birthdate column via SQL. The column value is being retrieved through user->birthdate but I cannot seem to save the values when i assign them. Is there anything I need to update on Laravel side?
I already tried recreating the model through artisan make:model User
I can assign other values and they are being saved except for the newly added column
$user = User::find($id);
$user->birthdate = $birthdate; //NOT BEING SAVED
$user->name = $name; //VALUE IS BEING SAVED
$user->save();
Retrieving is no problem
$user = User::find($id);
echo $user->birthdate; // Echoes successfully
Any help would be greatly appreciated
In the user model you need to add birthdate to fillable array
protected $fillable = ['name', 'email', 'birthdate', 'password'];

Resources