I'm sure I'm doing something wrong but can't figure out what it is.
In a controller I have a method which executes:
$estimate = Estimate::create(
['session_id' => 'test']
);
Model:
use HasFactory;
protected $fillable = ['width, height, direction_id, media_id, coating_id, shape_id, amount, qty, session_id'];
Estimate is related to estimates in my db.
When triggered an estimate record is created but the field 'session_id' is blank.
session_id is a VARCHAR 191.
Any idea why this is happening?
You define your $fillable wrong. It should be an array of strings:
protected $fillable = [
'width',
'height',
'direction_id',
'media_id',
'coating_id',
'shape_id',
'amount',
'qty',
'session_id',
];
Related
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.
I'm building an application with 4 tables: Films, Actors, Categories and Images
There is a Polymorph relation between Images in one side and Films, Actors and Categories in the other side.
These are my models:
- Actor
class Actor extends Model
{
protected $fillable = ['name', 'image_id', 'genre', 'slug',];
public function images()
{
return $this->morphMany('App\Comment', 'imageable');
}
}
- Category
class Category extends Model
{
protected $fillable = [ 'category', 'description', 'image_id', 'slug'];
public function images()
{
return $this->morphMany('App\Comment', 'imageable');
}
}
- Film
class Film extends Model
{
protected $fillable = ['name','image_id','description','slug','trailer','year','duration','age_id','language_id','category_id'];
public function images()
{
return $this->morphMany('App\Comment', 'imageable');
}
}
- Images
class Image extends Model
{
protected $fillable = [ 'image', 'imageable_id', 'imageable_type' ];
public function imageable()
{
return $this->morphTo();.
}
}
As far as I understand the "imageable_id" in Images table is the id (INCREMENT) of the position in the other tables (film->id, category->id or actor->id)
But the "imageable_id" must be also UNIQUE.
Here is my problem:
Let's say I create the first film and associate an image to it.
Image.id = 1, imageable_id = 1 (the id of the film), imageable_type = film
Second I create an actor and associate an image to it.
Image.id = 2, imageable_id = 1 (the id of the actor).... <-- ERROR
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '7' for key 'images_imageable_id_unique
Should I remove the AUTO_INCREMENT in all tables?
Any idea on how to solve that problem?
The Store methods in my 3 Controllers (CategoriesController, FilmsControllers and ActorControllers) are similar. (I share here just the Categoriescontrollers)
public function store(CategoriesRequest $request)
{
$file = $request->file('image');
$name = time() . '-' . $file->getClientOriginalName();
$file->move('images', $name);
$last_img = Image::orderBy('id', 'desc')->first();
$category = Category::create([
'category' => $request->category,
'description' => $request->description,
'slug' => str_slug($request->category, '-'),
'image_id' => $last_img->id + 1,
]);
$image = Image::create([
'image' => $name,
'imageable_type' => 'Category',
'imageable_id' => $category->id
]);
$category->save();
Session::flash('success', 'Category successfully created!');
return redirect()->route('categories.index');
}
But the "imageable_id" must be also UNIQUE.
It can't be unique with polymorphic relationships. If you want to use polymorphic relationships it really cannot be unique, as the polymorphic relationships are connected to multiple tables and each of those tables will have their own autoincrementing ids, which are unique on their respective table, but not unique across the database.
It's possible to have unique ids across multiple tables, but rather uncommon in MySQL.
The solution is to remove the unique index from you imageable_id column on the images table.
You probably want the combination of imagaeble_id and imageable_type to be unique, which will enforce a 1-to-1 relationship, which can be done on a MySQL level.
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
);
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'
];
if I have a model Student and it has three properties:
name
age
classroom_id
name and age are in fillable array.
So if I want to create a new student and assign his/her classroom_id, I have to do this:
$student = App\Student::create(
[
'name'=>$request->input('name'),
'age'=>$request->input('age')
]
);
$student->classroom_id = 1;//for example
$student->save();
is this right? And if this is right, actually I do insert action twice, right?
You can just update your $fillable array inside your model to include classroom_id and it will become mass assignable, meaning you don't need to do two inserts to get all the data in there.
As such, your $fillable array will look similar to this:
protected $fillable = ['name', 'age', 'classroom_id'];
And your create method similar to this:
$student = App\Student::create(
[
'name' => $request->input('name'),
'age' => $request->input('age'),
'classroom_id' => 1
]
);
This is the correct way, rather than running your insert twice which is unnecessary.