How I can save data in two tables simultaneously in laravel? - php

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 :)

Related

Laravel 6 : Duplicate database entry on polymorphisme relation save

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 ^^

How to output data in multipleSelect to laravel-admin form?

Model - Promo:
...
protected $table = 'promo';
...
public function locations()
{
return $this->belongsToMany(Cities::class, 'cities_promo');
}
Controller in laravel-admin
...
protected function form()
{
$location = Cities::pluck('name', 'id');
$form = new Form(new Promo);
$form->text('title', __('Title'));
$form->textarea('desc', __('Description'));
$form->multipleSelect('locations')->options($location);
return $form;
}
...
The bottom line is that it does not display the values that were previously selected and saved. An empty field is displayed there, where you can select values from the City model.
An intermediate solution was to use the attribute.
It is necessary that the format for multipleSelect (and others) was in array format [1,2,3 ... ,7].
In normal communication, an array of the form is transmitted:
{
['id' => 1,
'name' => 'Moscow',
...
],
['id' => 2,
'name' => 'Ekb',
...
],
}
Therefore, for formalization, I used a third-party attribute "Cities" to the model "Promo".
...
//Add extra attribute
//These attributes will be written to the database, if you do not want
//this, then do not advertise!
//protected $attributes = ['cities'];
//Make it available in the json response
protected $appends = ['cities'];
public function getCitiesAttribute()
{
return $this->locations->pluck('id');
}
public function setCitiesAttribute($value)
{
$this->locations()->sync($value);
}
If there are other suggestions, I am ready to listen.
Thank.
change $location to
$location = Cities::All()->pluck('name', 'id');
you can return $location to know it has value or not
also you can set options manually
$form->multipleSelect('locations')->options([1 => 'foo', 2 => 'bar', 'val' => 'Option name']);
to know it works

Laravel: Updating hasMany/BelongTo relation

I have a master table jobs with multiple location in separate table job_location. Now I am not able to update/delete, if extra rows found from job_location. Now why I am saying DELETE is because sync() did this, but it's related to many-to-many relation. I am new to laravel, just trying to get eloquent approach to achieve this, otherwise deleting all rows and inserting can be done easily OR updating each and delete remaining is also an option but I wonder Laravel has something for this.
In every request I get multiple job locations(with unchanged/changed city,phone_number,address) which is creating trouble.
Some codeshots:
Model: [Job.php]
class Jobs extends Model
{
protected $fillable = [
'job_id_pk', 'job_name','salary'
];
public function joblocation() {
return $this->hasMany('\App\JobLocation', 'job_id_fk', 'job_id_pk');
}
}
Model:[JobLocation.php]
class JobLocation extends Model
{
protected $fillable = [
'jobl_id_pk', 'job_id_fk','city', 'address', 'phone_number'
];
public function job() {
return $this->belongsTo('\App\Jobs', 'job_id_fk', 'job_id_pk');
}
}
Controller:[JobController.php]
function jobDetail() {
if($params['jid']) {
// update
$obj = \App\Jobs::find($params['jid']);
$obj->job_name = $params['name'];
$obj->salary = $params['salary'];
$obj->save();
} else {
// create new
$data = array(
'job_name' => $params['name'],
'salary' => $params['salary'],
);
$obj = \App\Jobs::create($data);
}
// don't bother how this $objDetail has associative array data, it is processed so
foreach ($params['jobLocations'] AS $key => $objDetail) {
$jobLoc = new \App\JobLocation;
$jobLoc->city = $objDetail['city'];
$jobLoc->phone_number = $objDetail['phone_number'];
$jobLoc->address = $objDetail['address'];
$jobLoc->job()->associate($obj);
$obj->jobLoc()->save($jobLoc);
}
}
In this approach I am able to save all job locations, but I am using same function to update also. Please tell how I can update jobLocations if present. I am ok to loose previous entries, but it would be good if previous gets updated and new get entered OR if we have extra entries they get deleted. I know sounds weird but still guide me a way.
Yea, you cannot use the same function, do this
$jobs = \App\Jobs::find($params['jid']);
foreach ($params['jobLocations'] as $key => $objDetail) {
$joblocation = $jobs->joblocation->where('jobl_id_pk', $objDetail['some_id'])->first();
//here update you job location
$joblocation->save();
}
Something like this:
Controller:[JobController]
public function jobDetail() {
if( !empty($params['jid']) ) {
// update
$job = \App\Jobs::find($params['jid']);
$job->job_name = $params['name'];
$job->salary = $params['salary'];
$job->save();
} else {
// create new
$data = array(
'job_name' => $params['name'],
'salary' => $params['salary'],
);
$job = \App\Jobs::create($data);
}
$locationDetails = !empty($params['jobLocations']) ? $params['jobLocations'] : [];
$jobLocations = array_map(function($location) use($job) {
$location = array_merge($location, [ 'job_id_fk' => $job->job_id_pk ]);
return \App\JobLocation::firstOrNew($location);
}, $locationDetails);
$job->jobLocations()->saveMany($jobLocations);
}

Laravel: Add data to the $request->all()

I wan to add the sector id to the request but when I submit the data nothing store on it.
Here is my code
public function store(QuestionRequest $request)
{
$data = $request->all();
Question::create($data);
$sectors = Sector::lists('id');
foreach($sectors as $sector){
CustomizeQuestion::create(array_add($request->all(), 'sector_id', $sector));
}
flash()->success('New question has been added.');
return redirect('questions');
}
I have tried this code also but it is the same :
public function store(QuestionRequest $request)
{
$data = $request->all();
Question::create($data);
$sectors = Sector::lists('id');
foreach($sectors as $sector){
$data['sector_id'] = $sector;
CustomizeQuestion::create($data);
}
flash()->success('New question has been added.');
return redirect('questions');
}
If you only want to add one 'id' to your request as you said, you can simply do this before creating anything :
$data = $request->all();
$data['sector_id'] = whatever you want;
Question::create($data);
Or like the second way you showed.
If this approach doesn't work verify if you have your properties specified in the model's fillable array and if you are using the correct property name as you specified in your migration.
First of all check your CustomizeQuestion model. sector_id should be in $fillable array. Example:
protected $fillable = [
'sector_id',
'more',
'and_more'
];
And if your form return only one id to store method no need to use foreach or list your id. Simply do this:
$data['sector_id'] = $request['id'];
CustomizeQuestion::create($data);

Laravel visitors counter

I'm trying to build a visitors counter in Laravel....
I don't know what the best place is to put the code inside so that it loads on EVERY page... But I putted it inside of the routes.php....
I think I'll better place it inside of basecontroller?
But okay, My code looks like this now:
//stats
$date = new \DateTime;
$check_if_exists = DB::table('visitor')->where('ip', $_SERVER['REMOTE_ADDR'])->first();
$get_visit_day = DB::table('visitor')->select('visit_date')->where('ip', $_SERVER['REMOTE_ADDR'])->first();
$value = date_create($get_visit_day->visit_date);
if(!$check_if_exists)
{
DB::table('visitor')->insert(array('ip' => $_SERVER['REMOTE_ADDR'], 'hits' => '1', 'visit_date' => $date));
}else{
DB::table('visitor')->where('ip', $_SERVER['REMOTE_ADDR'])->increment('hits');
}
$value = date_create($get_visit_day->visit_date);
if ($check_if_exists && date_format($value, 'd') != date('d')) {
DB::table('visitor')->insert(array('ip' => $_SERVER['REMOTE_ADDR'], 'hits' => '1', 'visit_date' => $date));
}
That works fine, but the problem is, my database columns always add a new value.
So this is my database:
From the table 'visitor'.
It keeps adding a new IP, hit and visit_date...
How is it possible to just update the hits from today (the day) and if the day is passed, to set a new IP value and count in that column?
I'm not 100% sure on this, but you should be able to do something like this. It's not tested, and there may be a more elegant way to do it, but it's a starting point for you.
Change the table
Change the visit_date (datetime) column into visit_date (date) and visit_time (time) columns, then create an id column to be the primary key. Lastly, set ip + date to be a unique key to ensure you can't have the same IP entered twice for one day.
Create an Eloquent model
This is just for ease: make an Eloquent model for the table so you don't have to use Fluent (query builder) all the time:
class Tracker extends Eloquent {
public $attributes = [ 'hits' => 0 ];
protected $fillable = [ 'ip', 'date' ];
protected $table = 'table_name';
public static function boot() {
// Any time the instance is updated (but not created)
static::saving( function ($tracker) {
$tracker->visit_time = date('H:i:s');
$tracker->hits++;
} );
}
public static function hit() {
static::firstOrCreate([
'ip' => $_SERVER['REMOTE_ADDR'],
'date' => date('Y-m-d'),
])->save();
}
}
Now you should be able to do what you want by just calling this:
Tracker::hit();
Looking at your code and reading your description, I’m assuming you want to calculate number of hits from an IP address per day. You could do this using Eloquent’s updateOrNew() method:
$ip = Request::getClientIp();
$visit_date = Carbon::now()->toDateString();
$visitor = Visitor::findOrNew(compact('ip', 'visit_date'));
$visitor->increment('hits');
However, I would add this to a queue so you’re not hitting the database on every request and incrementing your hit count can be done via a background process:
Queue::push('RecordVisit', compact('ip', 'visit_date'));
In terms of where to bootstrap this, the App::before() filter sounds like a good candidate:
App::before(function($request)
{
$ip = $request->getClientIp();
$visit_date = Carbon::now()->toDateString();
Queue::push('RecordVisit', compact('ip', 'visit_date'));
);
You could go one step further by listening for this event in a service provider and firing your queue job there, so that your visit counter is its own self-contained component and can be added or removed easily from this and any other projects.
Thanks to #Joe for helping me fulley out!
#Martin, you also thanks, but the scripts of #Joe worked for my problem.
The solution:
Tracker::hit();
Inside my App::before();
And a new class:
<?php
class Tracker Extends Eloquent {
public $attributes = ['hits' => 0];
protected $fillable = ['ip', 'date'];
public $timestamps = false;
protected $table = 'visitor';
public static function boot() {
// When a new instance of this model is created...
static::creating(function ($tracker) {
$tracker->hits = 0;
} );
// Any time the instance is saved (create OR update)
static::saving(function ($tracker) {
$tracker->visit_date = date('Y-m-d');
$tracker->visit_time = date('H:i:s');
$tracker->hits++;
} );
}
// Fill in the IP and today's date
public function scopeCurrent($query) {
return $query->where('ip', $_SERVER['REMOTE_ADDR'])
->where('date', date('Y-m-d'));
}
public static function hit() {
static::firstOrCreate([
'ip' => $_SERVER['REMOTE_ADDR'],
'date' => date('Y-m-d'),
])->save();
}
}
Named 'tracker' :)
public $attributes = ['hits' => 0];
protected $fillable = ['ip', 'date'];
public $timestamps = false;
protected $table = 'trackers';
public static function boot() {
// When a new instance of this model is created...
parent::boot();
static::creating(function ($tracker) {
$tracker->hits = 0;
} );
// Any time the instance is saved (create OR update)
static::saving(function ($tracker) {
$tracker->visit_date = date('Y-m-d');
$tracker->visit_time = date('H:i:s');
$tracker->hits++;
} );
}
// Fill in the IP and today's date
public function scopeCurrent($query) {
return $query->where('ip', $_SERVER['REMOTE_ADDR'])
->where('date', date('Y-m-d'));
}
public static function hit() {
/* $test= request()->server('REMOTE_ADDR');
echo $test;
exit();*/
static::firstOrCreate([
'ip' => $_SERVER['REMOTE_ADDR'],
'date' => date('Y-m-d'),
// exit()
])->save();
}
In laravel 5.7 it required parent::boot() otherwise it will show Undefined index: App\Tracker
https://github.com/laravel/framework/issues/25455
This is what i did its very basic but can easily build it up and add filters on visitors per day month year etc..
i added the following code to the web.php file above all the routes to run on each request on the site so no matter what page the visitor landed on it will save the ip addess to the database only if its unique so one visitor wont keep addding to the visitor count
// Web.php
use App\Models\Visitor
$unique_ip = true;
$visitors = Visitor::all();
foreach($visitors as $visitor){
if($visitor->ip_address == request()->ip()){
$unique_ip = false;
}
}
if($unique_ip == true){
$visitor = Visitor::create([
'ip_address' => request()->ip(),
]);
}
Routes...
the model is straight forward just has a ip addess field

Categories