How to delete file in my database Laravel - php

How do I delete files in the database, because when I click delete the data in the folder is deleted, but the data in the file_rekap tables don't want to be deleted, but the ones in the rekap table are deleted
RekapController:
public function delete_rekap($id){
$data = rekap::findOrfail($id);
$files = file_rekap::where("rekap_id", $data->id)->get();
foreach($files as $file){
if (File::exists("rekap_file/".$file->file)) {
File::delete("rekap_file/".$file->file);
}
}
$data->delete();
return redirect()->route('rekap')->with('success','Data berhasil dihapus');
}
public function files($id){
$data = rekap::find($id);
if(!$data) abort(404);
$files = $data->files;
return view ('file_rekap',compact('data','files'));
}
Model rekap and file_rekap
class rekap extends Model{
use HasFactory;
protected $fillable = [
'customer',
'vessel',
'scopejob',
'pergantian_sparepart',
'teknisi',
'tahun',
'keterangan',
];
public function files(){
return $this->hasMany(file_rekap::class);
}
}
/////////////////////////////////
class file_rekap extends Model
{
use HasFactory;
protected $fillable = [
'file',
'rekap_id',
];
public function rekaps(){
return $this->belongsTo(rekap::class);
}
}
and script in my rekap_blade
#csrf
<div class="modal-body">
<div class="form-group">
<input type="file" name="import_excel" required>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save changes</button>
</div>
</form>
</div>
</div>
</div>
<div class="row g-2 align-items-center m-2">
<form action="/rekap" method="GET">
<div class="input-group">
<input type="text" class="form-control " placeholder="Cari..." name="search">
<button class="btn btn-info" type="submit">Search</button>
</div>
</div>
</form>
<table class="table">
<thead class="thead ">
<tr>
<th scope="col">Customer</th>
<th scope="col">Vessel/Unit</th>
<th scope="col">Scope Job</th>
<th scope="col">Pergantian Spare Part</th>
<th scope="col">Teknisi</th>
<th scope="col">Bulan Tahun</th>
<th scope="col">Catatan</th>
<th scope="col">Total File</th>
<th scope="col">Aksi</th>
</tr>
</thead>
<tbody>
#foreach ($data as $row)
<tr>
<td>{{ $row->customer}}</td>
<td>{{ $row->vessel}}</td>
<td>{{ $row->scopejob}}</td>
<td>{{ $row->pergantian_sparepart}}</td>
<td>{{ $row->teknisi}}</td>
<td>{{ $row->tahun}}</td>
<td>{{ $row->keterangan}}</td>
<td>{{ $row->files->count()}}</td>
<td>
FILE
EDIT
<a href="#" class="btn btn-danger delete m-1" data-id="{{ $row->id}}" data-customer="{{ $row->customer}}" >DELETE</a>
</td>
</tr>
#endforeach
</tbody>
</table>
</tbody>
</table>
{{ $data->links() }}
</div>
</div>
</div>
#endsection
<script>
$('.delete').click(function(){
var rekapid = $(this).attr('data-id');
var customer = $(this).attr('data-customer');
swal({
title: "Yakin",
text: "Kamu akan menghapus data dengan nama "+customer+" ",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
window.location = "/delete_rekap/"+rekapid+" "
swal("Data Berhasil Terhapus", {
icon: "success",
});
} else {
swal("File Anda Aman");
}
});
});
</script>
How ti fix it ?

If you want to work with other developers in the future, make sure to work to common coding standards, such as using upper camel case for classes. Also consider the correct indentation.
Anyway, you don't actually delete the database record when deleting files
$files = file_rekap::where("rekap_id", $data->id)->get();
foreach($files as $file) {
if (File::exists("rekap_file/".$file->file)) {
File::delete("rekap_file/".$file->file);
}
$file->delete();
}
This isn't the optimum case as a database query is executed for every loop over the files collection.
Better is to perform a separate delete
public function delete_rekap($id){
$data = rekap::findOrfail($id);
$files = file_rekap::where("rekap_id", $data->id)->get();
foreach($files as $file){
if (File::exists("rekap_file/".$file->file)) {
File::delete("rekap_file/".$file->file);
}
}
file_rekap::where("rekap_id", $data->id)->delete();
$data->delete();
return redirect()->route('rekap')->with('success','Data berhasil dihapus');
}
if you have a relationship set up, you can also delete via that
$data->file_recap()->delete();
make sure your data is not important when experimenting with delete

$status=unlink('data.txt');
// Delete a single file
File::delete($filename);

Related

How to display my JSON response in a table using Laravel?

I'm trying to create Live search in Laravel using AJAX with one of my tables. I watched a YouTube video on this and I got to around 18:00 min on the 21 minute video. At this point there was no LIVE search, but he was able to view the data in his table through the AJAX request. While the video wasn't perfect, I wasn't seeing the data appear in my table, I am getting the response, I see the data in the network tab, in the response tab of my console, but am unable to see it displayed on the web page, and I'm not getting any other errors.
web.php:
Route::get('/admin/job-seeker/search', 'AdminJobSeekerSearchController#index')->name('admin.job.seeker.search.index')->middleware('verified');
Route::get('/admin/job-seeker/search/action', 'AdminJobSeekerSearchController#action')->name('admin.job.seeker.search.action')->middleware('verified');
AdminJobSeekerSearchController.php:
public function index()
{
return view('admin.job-seeker.search.index'));
}
public function action(Request $request)
{
if($request->ajax())
{
$total_data = '';
$output = '';
$query = $request->get('query');
if($query != '')
{
$data = DB::table('employer_profiles')
->where('company_name', 'like', '%'.$query.'%')
->orWhere('company_address', 'like', '%'.$query.'%')
->orWhere('immediate_contact', 'like', '%'.$query.'%')
->get();
}
else
{
$data = DB::table('employer_profiles')
->orderBy('id', 'desc')
->get();
}
$total_row = $data->count();
if($total_row > 0)
{
foreach($data as $row)
{
$output .= '
<tr>
<td>'.$row->company_name.'</td>
<td>'.$row->company_address.'</td>
<td>'.$row->immediate_contact.'</td>
</tr>
';
}
}
else
{
$output = '
<tr>
<td colspan="5">No Data Found</td>
</tr>
';
}
$data = array(
'table_data' => $output,
'total_data' => $total_row
);
$str_data = implode(" ", $data);
echo $str_data;
}
}
index.blade:
#extends('layouts.admin')
#section('content')
#if (session('send-profile'))
<div class="alert alert-success">
{{ session('send-profile') }}
</div>
#endif
<div class="row">
<div class="col-md-12">
<!-- Topbar Search -->
<form class="navbar-search">
<div class="input-group">
<input type="text" class="form-control bg-lightblue border-0 small text-white border-dark" name="search" id="search" placeholder="Search for..." aria-label="Search" aria-describedby="basic-addon2">
<div class="input-group-append">
<button class="btn btn-success" type="button">
<i class="fas fa-cannabis"></i>
</button>
</div>
</div>
</form><br>
</div>
<div class="col-md-12">
<table class="table table-hover table-responsive-sm">
<thead class="thead-dark">
<tr>
<th scope="col">Total Data : <span id="total_records"></span></th>
<th scope="col">Company Name</th>
<th scope="col">Immediate Contact</th>
<th scope="col">Address</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
#stop
#push('scripts')
<script>
$(document).ready(function() {
fetch_customer_data();
function fetch_customer_data(query = '')
{
$.ajax({
url:"{{ route('admin.job.seeker.search.action') }}",
method: 'GET',
data: {query:query},
dataType:'json',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success:function(data)
{
$('tbody').html(data.table_data);
$('#total_records').text(data.total_data);
}
})
}
});
</script>
#endpush
The data from the table is supposed to be displayed inside of the <tbody></tbody> tags. Below is a screenshot of the data in my network tab, in the response tab in my console.
Try to return the $data array like this:
return response()->json($data);

Laravel Searchform and Delete not working

So I have a search form for offices and delete for offices, also edit it those 2 were working before. But after I changed and fix edit form and button those are not working anymore the search is not working it shows this error
Undefined variable: building (View: C:\xampp\htdocs\Eguide\resources\views\search.blade.php)
The delete also show this error but it works after I go back to the office page it deleted it but it shows an error message:
Trying to get property 'name' of non-object (View: C:\xampp\htdocs\Eguide\resources\views\building.blade.php)
DD offices result
This is the controller for search and delete
OfficeController.php
public function index()
{
$search = \Request::get('search');
$offices = Office::where('name','like','%'.$search.'%')->get();
return view('search',compact('offices','search'));
}
public function store(Request $request, $id)
{
$office = new Office();
$office->name =$request->officename;
$office->floor = $request->floor;
$office->building_id = $id;
$office->save();
\Session::flash('building_flash', 'Created successfully!');
return redirect()->route('building', $id);
}
public function show($id)
{
$office = Office::find($id);
return view('office')->withOffice($office);
}
public function edit($id, $office_id) {
$office = Office::find($office_id);
return view('editoffice', compact('office', 'id'));
}
public function update(Request $request, $id, $office_id)
{
// echo $id.'--'.$office_id;exit;
//$office = Office::find($id);
$office = Office::find($office_id);
$office->name = $request->officename;
$office->floor = $request->floor;
$office->update();
\Session::flash('building_flash', 'Updated successfully!');
return redirect()->route('building', $id);
}
public function destroy($id)
{
$office = Office::find($id);
$office->delete();
\Session::flash('building_flash_delete', 'Deleted successfully!');
return redirect()->route('building', $id);
}
}
search.blade.php
No error in search when I remove this
Edit
<div class="search">
{!! Form::open(['method'=> 'GET','url'=>'offices','role'=>'search']) !!}
<div class="input-group col-xs-4 col-md-6" >
<input type="text" name="search" class="form-control" placeholder="Search...">
<span class="input-group-btn">
<button type="submit" class="btn btn-info btn-md">Search
</button>
</span>
</div>
{!! Form::close()!!}
</div>
<hr>
<table class="table">
<thead>
<th>Office Name</th>
<th>Belongs to</th>
<th>Office Floor</th>
</thead>
<tbody>
#foreach($offices as $office)
<tr>
<td>{{optional($office)->name}}</td>
<td>{{$office->building->name}}</td>
<td>{{$office->floor}}</td>
<td class="a">
#if(!Auth::guest())
Edit
Delete
#endif
#endforeach
#endsection
I also have Building.php in app folder it has code like this
class Building extends Model
{
public $table = 'buildings';
public function offices(){
return $this->hasMany('App\Office');
}
}
Office.php
class Office extends Model
{
public function building(){
return $this->belongsTo('App\Building');
}
}
ROUTES
Route::get('/', 'BuildingController#index')->name('index');
Route::get('building/{id}', 'PageController#show')->name('building');
Route::get('office/{id}', 'OfficeController#show')->name('officeMenu');
Route::get('offices', 'OfficeController#index');
Route::group(['middleware' => ['auth']], function () {
Route::get('buildings/create', 'BuildingController#create')->name('createbform');
Route::post('building/create/store', 'BuildingController#saveBuilding')->name('createbuilding');
Route::get('building/{id}/edit', 'BuildingController#edit');
Route::post('building/{id}/edit', 'BuildingController#update')->name('editbuilding');
Route::get('building/{id}/delete', 'BuildingController#destroy');
Route::get('building/{id}/offices/create', 'OfficeController#create')->name('createofficeform');
Route::post('building/{id}/offices/create/store', 'OfficeController#store')->name('createoffice');
Route::get('building/{id}/offices/{office_id}/edit', 'OfficeController#edit')->name('editofficeform');
Route::post('building/{id}/offices/{office_id}/edit', 'OfficeController#update')->name('editoffice');
Route::get('offices/{id}/delete', 'OfficeController#destroy')->name('deleteoffice');
});
buildidng.blade.php
<div class="officebg">
<link href="https://fonts.googleapis.com/css?family=Anton" rel="stylesheet">
<div class="Bldgttl">
<div class="container">
<div class="row">
<div class="col-lg-12">
<img src="{{URL::to('/assets')}}/{{$building->picture}}" alt="" style="height:300px; width:500px;">
</div>
</div>
<div class="row">
<div class="col-lg-12">
{{$building->name}}
</div>
</div>
</div>
</div>
<div class="rows">
<div class="col-md-6 col-md-offset-3">
<div class="col-xs-4 col-md-6">
#if(!Auth::guest())
Create an Office
#endif
</div>
{!! Form::open(['method'=> 'GET','url'=>'offices','role'=>'search']) !!}
<div class="input-group col-xs-4 col-md-6" >
<input type="text" name="search" class="form-control" placeholder="Search...">
<span class="input-group-btn">
<button type="submit" class="btn btn-info btn-md">Search</i>
</button>
</span>
</div>
{!! Form::close()!!}
<table class="table">
<div class="ttitle">
<thead>
<th>Office Name</th>
<th>Office Floor</th>
</thead>
<tbody>
#foreach($offices as $office)
<tr>
<td>{{optional($office)->name}}</td>
<td>{{$office->floor}}</td>
<td class="a">
#if(!Auth::guest())
Edit
Delete
#endif
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
#endsection
You don't have a building defined in show.
public function show($id)
{
$office = Office::find($id);
return view('office')->withOffice($office);
}
What you can do is to load a building in show method
public function show($id)
{
$office = Office::find($id);
$building = Building::first();//some logic to find building
return view('office',['building' => $building, 'office' => $office]);
}
Your building.blade.php is trying to access the $building variable. Your show method in your controller is only passing $office as data. Since $building doesn't exist trying to get the name property of it is returning an error.
You need to either pass $building from the controller to the view, or if it is part of $office extrapolate $building from that variable.
public function show($id)
{
$office = Office::find($id);
$building = Buildng::where('id', '=', $office->building_id)->firstOrFail();
return view('office',compact('office', 'building'));
}

Eloquent query on relationship table

Hello i have two models Adress and Kontokorrent they have a one to one relationship. I would like to make a search function and search after Adress and Kontokorrent columns
My models:
Adress Model
class Adress extends Model
{
protected $table = "Adressen";
protected $primaryKey = 'Adresse';
public $timestamps = false;
public function scopeSearchAdress($query, $searchTerm)
{
return $query->where('LieferOrt', 'LIKE', '%'.$searchTerm.'%')
->orWhere('Name1', 'LIKE', '%'.$searchTerm.'%')
->orWhere('LieferStrasse', 'LIKE', '%'.$searchTerm.'%');
}
public function kontokorrent()
{
return $this->hasOne(Kontokorrent::class, 'Adresse');
}
}
Kontokorrent Model
class Kontokorrent extends Model
{
protected $table = "Kontokorrent";
protected $primaryKey = 'Adresse';
public $timestamps = false;
public function scopeSearchKto($query, $searchTerm)
{
return $query->where('Kto', 'LIKE', '%'.$searchTerm.'%');
}
public function adress()
{
return $this->belongsTo(Adress::class, 'Adresse');
}
}
Controller
class AdressesController extends Controller
{
public function index(Request $request)
{
$searchTerm = $request->input('searchTerm');
$adresses = Adress::whereHas('kontokorrent', function($query) use($searchTerm) {
$query->where('KtoArt', 'D')
->searchKto('K75688'); // this is working
// -> searchKto($searchTerm); this is NOT working
})->orderBy('Name1')
->searchAdress($searchTerm)
->paginate(60);
return view('adresse.index', compact('adresses', 'searchTerm'));
}
}
The search function in Adress model is working. Now i would like to search after the customer ID (Kto) in Kontokorrent. So i made a scope in Kontokorrent and chain it to the contoller search function.
->searchKto('K75688') .... this is working i get a result
->searchKto($searchTerm) .... this is not working when i entry the customer id in my input field and hit enter. I get a 0 row table.
View
#section('content')
<div class="row">
<div class="col-xs-12 col-md-12">
<form role="search" method="GET" action="/adresses">
<div class="input-group">
<input type="text" class="form-control" name="searchTerm" value="{{ isset($searchTerm) ? $searchTerm : '' }}" placeholder="Suche nach Name, Straße, Ort">
<div class="input-group-btn">
<button type="submit" class="btn btn-search btn-default">
Suchen...
</button>
</div>
</div>
</form>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-md-12">
<table class="table table-bordered">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Straße</th>
<th>Ort</th>
<th>PLZ</th>
<th>Land</th>
</tr>
</thead>
<tbody>
#if(count($adresses) > 0)
#foreach($adresses as $adress)
<tr>
<th scope="row">{{ $loop->iteration }}</th>
<td>
{{$adress->Anrede}} {{ $adress->Name1}}
#if($adress->kontokorrent)
<small>{{ $adress->kontokorrent->Kto }}</small>
#endif
</td>
<td>{{ $adress->LieferStrasse }}</td>
<td>{{ $adress->LieferOrt }}</td>
<td>{{ $adress->LieferPLZ }}</td>
<td>{{ $adress->LieferLand }}</td>
</tr>
#endforeach
#else
<tr><td colspan="6" class="text-center">Kein Eintrag gefunden.</td></tr>
#endif
</tbody>
</table>
</div>
</div>
{{ $adresses->appends(['searchTerm' => $searchTerm])->links() }}
#endsection
I don't understand why I get an empty table.

Error While Fetching db using eloquent

I have Tried to fetch data from MySQL db using eloquent in my laravel application it shows Parse Error here my code :
Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class design extends Model {
//Table Name
protected $table='designs';
//Primary key
public $primarykey='id';
// TimeStamp
public $timestamps=true;
}
Controller Page:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\design;
class designController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
$design=design::all();
//$design = design::select('Design No','Design Name','Chain Weight/Length','status')->where('status','=','Active')->get();
return view('pages.design')->with('design',$design);
}
}
page for listing:
the error occurring while using for-each
#extends('layouts.layout')
#section('content')
<div class="main">
<div class="container col-md-12 col-sm-12 col-xs-12">
<h2 class="text-center">Designs</h2>
#if(count($design)>=1)
<h2>Done</h2>
<div class="table-responsive">
<table class="table table-striped table-hover table-bordered">
<thead>
<tr>
<th>Design No</th>
<th>Design Name</th>
<th>Weight/Lenght</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach($design as $design)
<tr>
<td>{{$design->Design No}}</td>
<td>{{$design->Design Name}}</td>
<td>{{$design->Chain Weight/Length}}</td>
<td>
<button type="button" class="btn btn-warning">Edit</button>
<button type="button" class="btn btn-danger">{{$design->status}}</button>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
#endif
</div>
</div>
#endsection
it doesn't allow space in column name it should be in lower cases as design_no , design_name in your DB
and then fetch as
#foreach($design as $new_designs)
<td>{{$new_designs->design_no }}</td>
// and so on
#endforeach
Hope it will work.
try this
{{$design->{'Design No'} }}
Yous should try this:
Controller Page
public function index()
{
//
$designs=design::all();
return view('pages.design',compact('designs'));
}
View Page
#foreach($designs as $design)
<tr>
<td>{{$design->Design_No}}</td>
<td>{{$design->Design_Name}}</td>
<td>{{$design->Chain_Weight/Length}}</td>
<td>
<button type="button" class="btn btn-warning">Edit</button>
<button type="button" class="btn btn-danger">{{$design->status}}</button>
</td>
</tr>
#endforeach

How to update record 'pay' laravel?

I'm trying to update my 'pay' record in the DB after pressing a button in a table row, but it shows this error when pressing the button:
ErrorException in 0db55b8fee884912074e1a4700061051aeb18bcc.php line
15: Undefined variable: users (View:
/Users/mauricio/code/cnr/resources/views/pages/users.blade.php)
I don't know why it gives me that error when I have use the users variable before in the blade file.
Here is my Registration Controller:
<?php
namespace App\Http\Controllers;
use DB;
use App\User;
class RegistrationController extends Controller
{
public function updatePay(User $id)
{
DB::table('users')->where('id', $id)->update(['pay' => 1]);
return view('pages.users');
}
}
Welcome controller:
public function usersAdmin()
{
$users = DB::table('users')->get();
return view('pages.users', compact('users'));
}
Routes file:
// for admin only
Route::get('/users', 'WelcomeController#usersAdmin');
Route::post('/users/{id}', 'RegistrationController#updatePay');
Here is my view
#extends('layouts.master')
#section('content')
<table class="highlight">
<thead>
<tr>
<th data-field="id" hidden="">ID</th>
<th data-field="name">Nombre</th>
<th data-field="last_name">Apellidos</th>
<th style="text-align: right;">Acciones</th>
</tr>
</thead>
<tbody>
#foreach($users as $user)
<tr>
<td>{{$user->id}}</td>
<td>{{$user->name}}</td>
<td>{{$user->last_name}}</td>
<td style="text-align: right; width: 30em">
#if( $user->isAdmin )
{{"ADMINISTRADOR"}}
#elseif( $user->pay )
<a class="waves-effect waves-light btn yellow darken-2"><i class="material-icons left" style="margin:0">create</i></a>
<a class="waves-effect waves-light btn red darken-1"><i class="material-icons left" style="margin:0">delete</i></a>
#else
<form method="POST" action="/users/{{$user->id}}">
{{ csrf_field() }}
<button type="submit" class="waves-effect waves-light btn green lighten-1"><i class="material-icons left" style="margin:0">done</i></button>
</form>
#endif
</td>
</tr>
#endforeach
</tbody>
</table>
#endsection
You need to retrieve users and send it to the view similar like this:
Controllers:
public function methodName()
{
$users = User::all();
return view('path.to.view')->with(compact('users'));
}
Also, You have two choice to use:
First
public function updatePay($id)
Second
public function updatePay(User $user)
{
DB::table('users')->where('id', $user->id)->update(['pay' => 1]);
and instead of return view('pages.users'); use return redirect()->url('users'); in the updatePay method.

Categories