I try to save a morph relationship in my database, but when i try to save it I Have tow entry in every table use for the relation.
here is my client class
class Client extends Model
{
protected $guarded = [];
public function clientelle(){
return $this->morphTo();
}
}
my particulier class
class Particulier extends Model
{
protected $guarded = [];
public function client(){
return $this->morphOne(Client::class,'clientelle');
}
}
So when I try to save like that :
$particulier = new Particulier();
$particulier->nom = $request->nom;
$particulier->prenom = $request->prenom;
$particulier->save();
$particulier->client()->create(['telephone'=>$request->telephone,'adresse'=>$request->adresse,'email'=>$request->email]);
My database save two same recorde. Here is my problem.
So I have try diffrente thing to avoid it but I have error every time
delete $particulier->save(); but SQL error id don't exist
replace create([...]) by save([...]) or sync([...]) but don't work
Thank you in advance
So I have finally find a worst solution...
In your controller add int var and init it to 0 like that :
Private $checkDouble=0;
In place where you want save your relation create if block and put in all of your model save like that :
if($this->checkDouble==0) {
$this->checkDouble = $this->checkDouble + 1; //Increase your var value
$particulier = Particulier::create(['nom' => $request->nom, 'prenom' => $request->prenom]);
$particulier->client()->create(['telephone' => $request->telephone, 'adresse' => $request->adresse, 'email' => $request->email]);
}
And no more duplicate data
I know is really worst solution but I don't see any best solution ^^
Related
Hi everyone i have a many-to-many relationship between the turnos table and the dias table like this:
Currently, I'm doing the CRUD of the turnos table and for each turnos I have to assign many dias, I did it with the attach method.
Now the issue is in the edit method... how am I gonna get the assigned dias that is related to that turno so I can pass it to the view and the user can edit it?
If someone knows it please help me, I would appreciate it very much
//Dias Model
public function turnos()
{
return $this->belongsToMany(Turno::class);
}
//Turnos Model
public function dias()
{
return $this->belongsToMany(Dia::class);
}
// Controller
public function edit(Turno $turno)
{
// $dias = ??
return Inertia::render('Turnos/Editar', [
'turno' => $turno,
'dias' => ??
]);
}
The edit view Should looks like this:
You can load the relation with the load() method and just return the $turno variable that will contain the "turno" and the "dias".
public function edit(Turno $turno) {
$turno->load('dias');
return Inertia::render('Turnos/Editar', [
'turno' => $turno
]);
}
On the client side you can use v-model to fill your inputs.
Since I started with my first Laravel project I've been having the error
Trying to get property 'column_name' of non-object nonstop, and most of the time I've been able to fix it one way or another, but the problem is, I have no idea of why I get the error, or how can I prevent it. For example,
// In my controller I have this domPDF function...
public function pdfgen(Request $request, $id) {
$data = Table::find($id);
View()->share('data', $data);
if ($request -> has('download')) {
$pdf = PDF::loadView('pdf/pdfgen');
return $pdf ->download('pdfgen.pdf');
}
return view('pdf/pdfgen');
}
// In my blade file I have a table calling this column...
<td>{{ $data->column }}</td>
// and this link making the request in the pdfgen function...
<a class="btn btn-primary" href="{{ route('pdfgen', ['download'=>'pdf']) }}">Download PDF</a>
// And in my routes of web.php...
Route::get('/pdfgen/{id}', array('as' => 'pdfgen', 'uses' => 'PDFController#pdfgen'));
and whenever I press that download link, I get a Whoops page with the trying to get property 'column' of non-object (View: /usr/src/workapp/resources/views/pdf/pdfgen.blade.php). Why am I getting this error and not the open/save dialog?
EDIT: Forgot to add, before trying to get specific data with $id, I called the whole table ($data = Table::all();) and used a #foreach in the blade view to print it in the table
EDIT 2: Adding the model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Table extends Model
{
protected $table = 'table';
protected $primaryKey = 'id';
public $incrementing = false;
protected $fillable = [
// all columns are strings, even id
'id',
'column',
'column2',
'column3',
];
public function table2()
{
return $this->hasMany('App\Table2');
}
}
When you do find($id) and the record is not present, it returns null. So if you try to access any property ->column, it will throw error.
You can either do findOrFail($id) or have condition if (is_null($data)) or on frontend have $data->column ?? 'defaultvalue
'
Now, the second situation where your model is present but you still get error, do :
$data = Table::find($id);
dd(array_keys($data->toArray()));
You should see the column you are trying to access if it is present.
Lastly, if it is not present in above step but is there in the table, then check for protected $hidden = [] setting of your model which essentially hides certain columns.
This happend because your $data might be null and your record with given $id might not exists in your database.
Try to change your code like below:
Table::findOrFail($id);
From now on if your table with given id doesn't exist, it'll automatically return 404 page.
I would like to hide my foreign_key on JSON response :
return Response::json(['type' => 'success', 'data' => $my_object, 'status' => 200], 200);
I added in my model :
protected $hidden = ['fk_category_id'];
My foreign key is hide !
But in my controller I have this :
$new_question = $this->question_repository->create([
'text' => $question->text,
'fk_category_id' => 2,
]);
The problem : I don't create a new object in my database, the field fk_category_id is NULL, I think I have no access to this field
My foreign key in my JSON response it's hide (great!) but I can't set my foreign key in my database when I created new entry.
add this to your model
protected $fillable = [..,'fk_category_id','text'];
you are attempting to do mass assignment, fillable is a whitelist which field will be fillable by mass assignment. .. means you can add whatever field you want there.
I saw your entity in your last (deleted) question. Add a setter function, then you can call that! Your protected and private properties will remain hidden!
class MyEntity
{
private $hidden;
public function getHidden()
{
return $this->hidden;
}
public function setHidden($value)
{
$this->hidden = value;
}
// the rest of your code etc
}
Update Method:
public function update(UserUpdateRequest $request, Users $uzytkownik)
{
$this->authorize('update', $uzytkownik);
if ( $uzytkownik->update([
'birth' => $request->birth,
'sex' => $request->sex,
'about' => $request->about,
]) )
{
return 1;
}
return 0;
}
On update here in page 1 appears. Like it did the thing.
But in db nothing has changed.
$uzytkownik is proper user, and
This is the dd($uzytkownik);
And below dd($request->birth.'---'.$request->sex.'---'.$request->about); which shows proper inputs
Why it doesn't work properly?
As per the documentation
Mass Assignment
You may also use the create method to save a new model in a single line. The inserted model instance will be returned to you from the method. However, before doing so, you will need to specify either a fillable or guarded attribute on the model, as all Eloquent models protect against mass-assignment by default.
You need to make sure $fillable or $guarded is correctly set otherwise changes may not be persistant.
You can do what you want like this too:
public function update(UserUpdateRequest $request, Users $uzytkownik)
{
$this->authorize('update', $uzytkownik);
$uzytkownik->birth = $request->birth;
$uzytkownik->sex = $request->sex;
$uzytkownik->about = $request->about;
if ( $uzytkownik->save() )
{
return 1;
}
return 0;
}
I have the following data mode
l
Detalle_Servicio has many Material_Usado and Material_Usado belongs only Detalle_Servicio
When I save values in Material_Usado should know the ID Detelle_Servido, but as I can not do that. I have the following code
Route
Route::post('/upload', function(){
$path = public_path().'/servicios';
try{
$upload_success1 = Input::file('foto1')->move($path,'1');
$upload_success2 = Input::file('foto2')->move($path,'2');
$upload_success3 = Input::file('foto3')->move($path,'3');
$upload_success4 = Input::file('foto4')->move($path,'4');
}catch(Exception $e) {
$e->getMessage();
}
$input = Input::get('json');
$json = json_decode($input);
if($upload_success1 && $upload_success2 && $upload_success3 && $upload_success4) {
//DB::insert("INSERT INTO Detalle_Servicio (RutaFoto1, RutaFoto2, RutaFoto3, RutaFoto4, FechaTermino, Latitud, Longitud, Servicio_idServicio) values(?,?,?,?,?,?,?,?)", array($path.'1', $path.'2', $path.'3', $path.'4',$json->termino, $json->latitud, $json->longitud, $json->idServicio));
$entradas = array(
'RutaFoto1' => $path.'1',
'RutaFoto2' => $path.'2',
'RutaFoto3' => $path.'3',
'RutaFoto4' => $path.'4',
'FechaTermino' => $json->termino,
'Latitud' => $json->latitud,
'Longitud' => $json->longitud,
'Servicio_idServicio' => $json->idServicio
);
Detalle_Servicio::create($entradas);
$array = array('Code' => '202', 'Message' => 'Done');
return Response::json($array);
} else {
$array = array('Code');
return Response::json('error', 400);
}
});
You can see that I get a JSON containing the values that I store in the database
I keep the data in the database of the Detalle_Servicio table but then I need to save some data in Material _Usado but I need the ID that was generated when you save the data in the table Detalle_Servicio
Model
class Detalle_Servicio extends Eloquent{
protected $table = 'Detalle_Servicio';
protected $primaryKey = 'idDetalle_Servicio';
protected $fillable = array('RutaFoto1', 'RutaFoto2', 'RutaFoto3', 'RutaFoto4', 'FechaTermino', 'Latitud', 'Longitud', 'Servicio_idServicio');
public function servicio(){
return $this->belongsTo('Servicio', 'idServicio'); //le pertenece a
}
public function material_usado(){
return $this->hasMany('Material_Usado', 'idMaterial_Usado');
}
}
and
class Material_Usado extends Eloquent{
protected $table = 'Material_Usado';
protected $primaryKey = 'idMaterial_Usado';
public function detalleServicio(){
return $this->belongsTo('Detalle_Servicio', 'idDetalle_Servicio');
}
}
how can I do it?
When you use this:
Detalle_Servicio::create($entradas);
It returns the model instance that was just created so you should do it like this way:
$Detalle_Servicio = Detalle_Servicio::create($entradas);
Now you can get the id of the created model using:
$Detalle_Servicio->id;
So, you may do something like this:
if($Detalle_Servicio = Detalle_Servicio::create($entradas)) {
$id = $Detalle_Servicio->id;
// ...
}
I don't really understand why you have this function in routes.php. Unless this is for example only...then you should have this a controller which will save the models in order.
First save the first model and then simply retrieve the foreign key that you need using something like this:
$serviceDetail = new Detalle_Servicio;
$serviceDetail->rutaFoto1 = Input::get('upload_success1');
etc..
$serviceDetail->save();
if ($serviceDetail->id)
{
$serviceDetail->material_usado()->attach($serviceDetail->id);
}
hope I understood the question :)