Update hidden value after soft deleting in Laravel - php

I have four tables:
Agroindustria
Pessoa
PessoaJuridica
Endereco
. Here are their Models:
Agroindustria
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Agroindustria extends Model
{
use SoftDeletes;
protected $table = "agroindustria";
protected $primaryKey = "CodAgroindustria";
public $incrementing = false;
protected $keyType = 'string';
public $fillable = ['CodAgroindustria, Porte'];
public $hidden = ['created_at', 'updated_at', 'deleted_at'];
public function pessoa () {
return $this->setConnection('diana')->hasOne(Pessoa::class, 'CodPessoa', 'CodAgroindustria');
}
public function pessoajuridica()
{
return $this->setConnection('diana')->hasOne(PessoaJuridica::class, 'CodPessoa', 'CodEndereco');
}
public function endereco()
{
return $this->setConnection('diana')->hasOne(PessoaJuridica::class, 'CodEndereco', 'CodEndereco');
}
public function estado(){
return $this->setConnection('diana')->hasOne(Estado::class, 'CodEstado', 'estado');
}
public function cidade(){
return $this->setConnection('diana')->hasOne(Cidade::class, 'CodCidade', 'cidade');
}
}
Pessoa:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Pessoa extends Model
{
// use SoftDeletes;
protected $table = "pessoa";
protected $primaryKey = "CodPessoa";
public $incrementing = false;
protected $keyType = 'string';
protected $connection = "diana";
public $hidden = ['created_at', 'updated_at', 'EXCLUIDO', 'LastSend'];
public $fillable = ['email', 'TelRes', 'TelCel'];
public function endereco()
{
return $this->hasOne('App\Endereco', 'CodEndereco', 'CodEndereco');
}
public function pessoafisica()
{
return $this->hasOne('App\PessoaFisica', 'CodPessoaFisica', 'CodPessoa');
}
public function pessoajuridica()
{
return $this->hasOne('App\PessoaJuridica', 'CodPessoaJuridica', 'CodPessoa');
}
}
The PessoaJuridica and Endereco Models are pretty much the same as the Pessoa Model.
When I soft delete my Agroindustria, the deleted_at column updates successfully, but I'm struggling with updating the EXCLUIDO column values from 0 to 1 in my other models.
Here's the delete function I created in my AgroindustriaController:
public function deletar (Request $request)
{
try {
$Agroindustria = Agroindustria::where('CodAgroindustria', $request['CodAgroindustria']);
$Agroindustria->delete();
$Pessoa = Pessoa::findOrFail($request['CodPessoa']);
if ($Agroindustria->delete()) {
DB::table('Pessoa')->where('CodPessoa', $Pessoa->CodPessoa)
->update(array('EXCLUIDO' => 1));
}
return response()->json([
'error' => false,
'data' => [
'message' => 'Dados deletados com sucesso',
]
]);
} catch (Exception $e) {
return response()->json([
'error' => true,
'message' => [$e->getMessage()]
]);
}
}

second line in try
$Agroindustria->delete();
write this line like this
$dlt = $Agroindustria->delete();
after that in your if condition put this variable $dlt like this
if ($dlt) {
DB::table('Pessoa')->where('CodPessoa', $Pessoa->CodPessoa)
->update(array('EXCLUIDO' => 1));
}

Solved it by doing:
$Agroindustria = Agroindustria::where('CodAgroindustria', $request['CodAgroindustria']);
$dlt = $Agroindustria->delete();
if ($dlt) {
Pessoa::where('CodPessoa', $request['CodPessoa'])
->update(array('EXCLUIDO' => 1));
PessoaJuridica::where('CodPessoaJuridica', $request['CodPessoaJuridica'])
->update(array('EXCLUIDO' => 1));
Endereco::where('CodEndereco', $request['CodEndereco'])
->update(array('EXCLUIDO' => 1));
}
Thank you all!

Related

Addition of an ordinal number in the Laravel Model

I am beginner webdeveloper,
I use in my project Laravel 7 and maatwebsite/excel
I have this code:
namespace App\Models;
use App\Models\Reservation;
use Maatwebsite\Excel\Excel;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\Exportable;
class ReservationExport implements FromCollection, WithHeadings
{
use Exportable;
protected $date;
public function __construct(string $date)
{
$this->date = $date;
}
public function headings(): array
{
return [
'LP',
'ID Rezerwacji',
'Adres email',
'Token',
'Data',
'Godzina',
'Tor',
'Płeć',
];
}
public function collection()
{
$res = Reservation::select('id', 'id', 'email', 'token', 'date', 'hour', 'track', 'sex')->where('date', $this->date)->orderBy('time', 'ASC')->orderBy('track', 'ASC')->get();
foreach ($res as $val) {
$val->sex = ($val->sex == 1) ? 'kobieta' : 'mężczyzna';
}
return $res;
}
}
public function export(Request $request)
{
return Excel::download(new ReservationExport($request->input('query')), 'reservation-'.$request->input('query').'.xlsx');
}
This code generates an Excel document. It works fine. I would like to add a sequence number in 1 column (1,2,3 etc).
How can I do this?
My model:
class Reservation extends Model
{
protected $quarded = ['id'];
protected $fillable = ['email', 'token', 'date', 'hour', 'track', 'sex', 'time', 'people'];
public $timestamps = true;
protected $table = 'reservations';
}
Please help
try this
basically u need to add sn to heading then in your collection u need to a new key sn with calculated sequence number
hope it will work if not please tell me what error u r getting
<?php
use App\Models\Reservation;
use Maatwebsite\Excel\Excel;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\Exportable;
class ReservationExport implements FromCollection, WithHeadings
{
use Exportable;
protected $date;
public function __construct(string $date)
{
$this->date = $date;
}
public function headings(): array
{
return [
'SN', // sn new key adding
'LP',
'ID Rezerwacji',
'Adres email',
'Token',
'Data',
'Godzina',
'Tor',
'Płeć',
];
}
public function collection()
{
$res = Reservation::select('id', 'id', 'email', 'token', 'date', 'hour', 'track', 'sex')->where('date', $this->date)->orderBy('time', 'ASC')->orderBy('track', 'ASC')->get();
foreach ($res as $val) {
$val->sex = ($val->sex == 1) ? 'kobieta' : 'mężczyzna';
}
$res->map(function ($row,$key) {
return $row['sn'] = $key; // sn key added to collection
});
return $res;
}
}

how to get id of table in relationship to use in other table in this relation?

i have relation between Service and Services_Gallery one to many, and i want to use id of Service when i insert new image to Services_Gallery, and this is my Controller:
public function save(Request $request)
{
$this->validate($request,[
'image' => 'required|image|mimes:jpeg,jpg,png,svg|max:1024'
]);
$services_Gallery = new Services_Gallery();
$services_Gallery->image = $request->image->move('Uploads', str_random('6') . time() . $request->image->getClientOriginalName());
$services_Gallery->Service::all(id) = $request->service_id; //The problem here
$services_Gallery->save();
return back();
}
this is my Models:
class Service extends Model
{
protected $table = 'services';
protected $fillable = [
'en_main_title',
'ar_main_title',
'en_sub_title',
'ar_sub_title',
'en_content_title',
'ar_content_title',
'en_content',
'ar_content',
'priority',
];
public function gallery()
{
return $this->hasMany('App\Services_Gallery','service_id');
}
}
class Services_Gallery extends Model
{
protected $table = 'services_galleries';
protected $fillable = [
'image',
'service_id',
];
public function gallery(){
return $this->belongsTo('App\Service','service_id');
}
}
Exapmle:
$modelOfService = Service::where('param_x', $request->service_id)->first();
$id = $modelOfService->id;
Is that you need?

Save data into two tables at same time in laravel

I am trying to save datas into two different tables depends on selection(x-editable). Here is my code and Help me by pointing where i am doing mistake.
Result i am looking for: I change payment status pending to paid in TBL:Product, paid values also change 0 to 1 in TBL:Product_payment
TBL:Product
- product_id
- client_id
...
- status {paid/pending}
TBL:Product_payment
- product_id
- payment_id
....
- paid {1/0}
Controller:
public function update()
{
$inputs = Input::all();
if ($row = Product::with('payments')->find($inputs['pk']))
{
$row->$inputs['name'] = $inputs['value'];
if($row['status'] == 'paid') {
$row['paid'] = 1;
}
$row->save();
return $row;
}
Product.php(model)
class Product extends Eloquent
{
protected $primaryKey = 'product_id';
protected $table = 'products';
protected $fillable = array('client_id', 'date', 'amount', 'status', 'notes');
public function payments()
{
return $this->hasMany('ProductPayment');
}
}
ProductPayment.php(model)
class ProductPayment extends Eloquent
{
public $table = 'product_payments';
protected $primaryKey = 'product_payment_id';
protected $fillable = array('product_id', 'client_id', 'payment_method', 'amount_paid', 'paid');
public function product()
{
return $this->belongsTo('Products');
}
public function clients()
{
return $this->belongsTo('Clients');
}
}
Add a model event listener to boot in your AppServiceProvider for whenever an instance of Product is saved.
Product::saved(function ($product) {
$paymentStatus = [
'pending' => 0,
'paid' => 1,
];
if(array_key_exists($product->status, $paymentStatus))
{
ProductPayment::where('product_id', $product->id)
->update(['paid' => $paymentStatus[$product->status]]);
}
});

Laravel 5.4 How to responses JSON with Relationship?

I want to response JSON with Laravel that I have CategoryModel belongTo SongModel.
This is my CategoryModel
class CategoryModel extends Model
{
protected $table = 'categories';
protected $fillable = [
'id',
'name',
];
public function song()
{
return $this->hasMany(SongModel::class);
}
}
And this is my SongModel
class SongModel extends Model
{
protected $table = 'songs';
protected $fillable = [
'id',
'name',
'url',
'categories_id',
'singers_id',
'types_id',
];
public function category()
{
return $this->belongsTo(CategoryModel::class);
}
}
I want to response JSON with the relationship. I wrote:
class SongController extends Controller
{
public function index(SongModel $songModel)
{
$song = $songModel->category()->get();
return response()->json(["DATA" => $song], 201);
}
}
To do this you will just need to load the relationship before you return the response:
public function index(SongModel $songModel)
{
$songModel->load('category');
return response()->json(["DATA" => $songModel], 201);
}
https://laravel.com/docs/5.4/eloquent-relationships#lazy-eager-loading
Hope this helps!
Try this. return response()->json(["DATA" => $songModel->load('category')->toArray()], 201);
OR, you can use with('song')
lass SongController extends Controller
{
public function index(SongModel $songModel)
{
$song = $songModel::with('song')->get();
return response()->json(["DATA" => $song], 201);
}
}

Laravel retrieve values from foreign key

I have these models with their related db tables,at the moment I can retrieve all the requirement
Requirement::all()
but I just have a list of foreigns key (destination_id,applier_id,doc_id). How can i retrieve directly the row connected to that foreigns key?
class Requirement extends Model
{
protected $fillable = [
'required',
'destination_id',
'applier_id',
'doc_id'
];
public function destination()
{
return $this->belongsTo(Destination::class);
}
public function applier()
{
return $this->belongsTo(Applier::class);
}
public function doc()
{
return $this->belongsTo(Doc::class);
}
}
class Doc extends Model
{
protected $fillable = [
'type',
'description',
'note'
];
public function requirements()
{
return $this->hasMany(Requirement::class);
}
}
class Destination extends Model
{
protected $fillable = [
'country',
'passying_country',
'transfer_conditions',
'passing_conditions'
];
public function requirements()
{
return $this->hasMany(Requirement::class);
}
}
You can call with() function instead of all(). So if you try this following :
$requirements = Requirement::with('destination', 'applier', 'doc')->get();
Make it dd($requirements) and look the output.
Hope it will work.

Categories