I'm currently using "maatwebsite/excel": "3.1.10", recently switched from 2.x version, and I'm having a problem with displaying excel data from view that is using Eloquent relationship. Here's all my code below.
UsersEarningHistory.php:
<?php
namespace App\Exports;
use App\EarningHistory;
use Illuminate\Contracts\View\View;
use Maatwebsite\Excel\Concerns\FromView;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\AfterSheet;
use Maatwebsite\Excel\Concerns\WithMapping;
class UsersEarningHistory implements FromView, ShouldAutoSize, WithEvents, WithMapping
{
protected $history;
public function __construct($history = null)
{
$this->history = $history;
}
public function view(): View
{
return view('admin.commission.excel_table', [
'history' => $this->history ?: EarningHistory::all()
]);
}
public function registerEvents(): array
{
return [
AfterSheet::class => function(AfterSheet $event) {
$cellRange = 'A1:W1'; // All headers
$event->sheet->getDelegate()->getStyle($cellRange)->getFont()->setSize(14)->setBold($cellRange);
},
];
}
}
UserController where my method for exporting data is:
public function index(Request $request)
{
//
$active = $this->active;
$active[1] = 'commission';
view()->share('active', $active);
$breadcrumbs = [
['link' => '/admin', 'text' => 'Administration'],
['text' => 'Commission']
];
view()->share('breadcrumbs', $breadcrumbs);
$styles[] = '//cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.css';
view()->share('styles', $styles);
$scripts[] = '//cdn.jsdelivr.net/momentjs/latest/moment.min.js';
$scripts[] = '//cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.js';
$scripts[] = '/js/admin/commission.js';
view()->share('scripts', $scripts);
$history = new EarningHistory();
if ($request->filled('q')) {
$history = $history->whereHas('user', function ($query) use ($request) {
$query->where('username', 'like', '%' . $request->q . '%');
});
}
if ($request->filled('qn')) {
$history = $history->whereHas('user', function ($query) use ($request) {
$query->where('first_name', 'like', '%' . $request->qn . '%');
$query->orWhere('last_name', 'like', '%' . $request->qn . '%');
if (strpos( $request->qn, ' ') !== false) { // is both
$both = explode(" ",$request->qn);
if(isset($both[0]))
$query->orWhere('first_name', 'like', '%' . $both[0] . '%');
if(isset($both[1]))
$query->orWhere('last_name', 'like', '%' . $both[1] . '%');
}
});
}
if($request->filled('has_correct_ratio')) {
$history = $history->where('has_correct_ratio', $request->filled_correct_ratio);
}
if (!$request->filled('null')) {
$history = $history->where(function ($query) {
$query->where('personal_balance', '!=', 0)
->orWhere('group_balance', '!=', 0);
});
}
if ($request->filled('date')) {
$history = $history->whereBetween('created_at', [Carbon::parse('01.' . $request->date)->firstOfMonth(),
Carbon::parse('01.' . $request->date)->addMonth()->firstOfMonth()]);
}
if ($request->filled('export')) {
$date = $request->filled('date') ? 'Earning history for ' . Carbon::parse('01.' . $request->date)->format('F') :
'Earning history for all time';
return Excel::download( new UsersEarningHistory($history), $date.'history.xls');
}
$data['history'] = $history->paginate(15);
$data['request'] = $request;
return view('admin.commission.index', $data);
}
Export table blade:
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Name</th>
<th>Month</th>
<th>Amount</th>
<th>World Bonus</th>
<th>Total amount</th>
<th>Personal points</th>
<th>Group points</th>
{{--<td></td>--}}
</tr>
</thead>
<tbody>
#foreach($history as $obj)
<tr>
<td>
{{ $obj->user->first_name . ' ' . $obj->user->last_name }}
</td>
<td>{{$obj->created_at->format('F')}}</td>
<td>€{{ number_format($obj->personal_balance + $obj->group_balance, 2)}}</td>
<td>€{{ number_format($obj->world_bonus, 2)}}</td>
<td>€{{ number_format($obj->personal_balance + $obj->group_balance + $obj->world_bonus, 2)}}</td>
<td>
{{ intval($obj->personal_points) }}
</td>
<td>
{{ intval($obj->group_points) }}
</td>
<td>
{{ App\User::$_RANK[$obj->rank]['title'] }}
</td>
{{--<td align="center">--}}
{{--<a href="/admin/payouts/{{$obj->id}}" class="btn btn-primary btn-xs">--}}
{{--<i class="icon-eye"></i>--}}
{{--</a>--}}
{{--<!--TODO Prikaži akciju na osnovu trenutnog statusa-->--}}
{{--#if($obj->status=='pending')--}}
{{--<a href="javascript:;" class="ajax-action btn btn-sm btn-success" data-action="/ajax/payout-change-status" --}}
{{--data-obj-id="{{$obj->id}}" data-status="approved">#lang('form.approve')</a>--}}
{{--<a href="/admin/payouts/reject/{{$obj->id}}" class="btn btn-sm btn-danger" >#lang('form.reject')</a>--}}
{{--#endif--}}
{{--</td>--}}
</tr>
#endforeach
</tbody>
</table>
As you can see, I'm trying to get user name from his earning history, but when I try to export data, my excel file is empty, but it's not giving me any errors.
Note: EarningHistory is related with User model:
//EarningHistory model
public function user()
{
return $this->belongsTo('App\User', 'user_id', 'id')->withTrashed();
}
//User model
public function earning_history()
{
return $this->hasMany('App\EarningHistory');
}
Found a solution. My $history variable in UserController was returning Query builder, because I forgot to add ->get(); method :
return Excel::download( new UsersEarningHistory($history->get()), $date.'history.xls');
Now everything works as it should.
Related
please help me, I have an AJAX search form in Laravel. It searches through the database 'patients', where they have a row 'assigned', where they are assigned to the ID of a user. The user searches through the AJAX search form, in order to find the patient. I want the user to be able to search and the results to show only the patients assigned to him, I don't want the user to be able to search and look through all the patients in the database. Here is what I tried so far, but it does not really work, please give me some ideas:
PatientController.php
function searchPatients(Request $request)
{
if($request->ajax())
{
$output = '';
$query = $request->get('query');
if($query != '')
{
if(Auth::user() -> role == 'user'){
$data = DB::table('patients')
->where('assigned', auth()->user()->id)
->where('name', 'like', '%'.$query.'%')
->orWhere('city', 'like', '%'.$query.'%')
->orWhere('country', 'like', '%'.$query.'%')
->orderBy('id', 'desc')
->get();
}
if(Auth::user() -> role == 'admin' || Auth::user() -> role == 'photostudio'){
$data = DB::table('patients')
->where('name', 'like', '%'.$query.'%')
->orWhere('city', 'like', '%'.$query.'%')
->orWhere('country', 'like', '%'.$query.'%')
->orderBy('id', 'desc')
->get();
}
}
else
{
/*$data = DB::table('patients')
->orderBy('id', 'desc')
->get();*/
}
$total_row = $data->count();
if($total_row > 0)
{
foreach($data as $row)
{
$output .= '
<div class="col-md-12 text-center offset-md-9">
<a href='.route("admin.patient", ["id" => $row->id]) .' style="text-decoration:none; color:black;">
<div class="card-mt-3">
<div id="records-patients" class="records-patients">
<div class="card-header">
Пациент: '. $row -> name. '
</div>
<div class="card-body">
<h3>Телефон:'.$row -> phone.'</h3>
<h3>Имейл: '. $row-> email.'</h3>
</div>
</div>
</div>
</a>
</div>
';
}
}
else
{
$output = '
<tr>
<td align="center" colspan="5">Nothing found, please try again</td>
</tr>
';
}
$data = array(
'table_data' => $output,
'total_data' => $total_row
);
echo json_encode($data);
}
}
AJAX search form and frontend
<script>
$(document).ready(function(){
function fetch_customer_data(query = '')
{
$.ajax({
url:"{{ route('admin.patients.search') }}",
method:'GET',
data:{query:query},
dataType:'json',
success:function(data)
{
if(query !== ''){
$('#patientsshow').html(data.table_data);
$('#total_records').text(data.total_data);
}
}
})
}
$(document).on('keyup', '#search-patients', function(){
var query = $(this).val();
if(query !== ''){
fetch_customer_data(query);
}
});
});
</script>
<div class="row">
<div id="patientsshow">
</div>
</div>
You can define relationship between User and Patient models
class User extends Model
{
public function patients()
{
return $this->hasMany(Patient::class, 'assigned', 'id');
}
}
class Patient extends Model
{
public function user()
{
return $this->belongsTo(User::class, 'assigned', 'id');
}
}
Then in the controller you can just get the patients for the currently logged in user using the relationship
class PatientController extends Controller
{
public function index(Request $request)
{
$user = $request->user();
//or
$user = auth()->user();
$patients = $user->isAdmin ? Patient::all() : $user->patients;
//do other stuff with the collection and return response
}
}
Made this work by this one in PatientController.php
if(Auth::user()-> role == 'user'){
$data = Patient::where('assigned', auth()->user()->id)
->where('name', 'like', '%'.$query.'%')
->get();
}
I am using Laravel 7 and I want to use ajax for my pagination so that it would not refresh the whole page when I click for the next page. I searched up to solve my problem but it was not working and it would not go to the fetch() whenever I error_log() in controller. Whenever I click on page 2 it would error. In the console the error shown is:
app.js:16437 GET http://127.0.0.1:8000/ledger/fetch?page=2 500 (Internal Server Error)
In the storage/logs/laravel.log
[previous exception] [object] (BadMethodCallException(code: 0): Method Illuminate\\Database\\Eloquent\\Collection::links does not exist. at C:\\xampp\\htdocs\\final_Financial\\fin_book_09\\vendor\\laravel\\framework\\src\\Illuminate\\Support\\Traits\\Macroable.php:103)
LedgerController.php
public function index(Request $request)
{
$disableLedger = true;
$ledger = Ledger::orderBy('id', 'DESC')
->where('user_id', auth()->user()->id)
->paginate(5);
$ledgerCatType = DB::table('ledgers')
->orderBy('ledgers.id', 'DESC')
->join('categories', 'ledgers.cat_id', '=', 'categories.id')
->where('ledgers.user_id', auth()->user()->id)
->get('categories.type');
$category = Category::where('user_id', auth()->user()->id)->get();
return view('ledgers.index', [
'ledgers' => $ledger,
'categories' => $category,
'disableLedger' => $disableLedger,
'ledgerCatType' => $ledgerCatType
]);
}
function fetch(Request $request)
{
if ($request->ajax())
{
$ledger = Ledger::orderBy('id', 'DESC')
->where('user_id', auth()->user()->id)
->paginate(5);
$ledgerCatType = DB::table('ledgers')
->orderBy('ledgers.id', 'DESC')
->join('categories', 'ledgers.cat_id', '=', 'categories.id')
->where('ledgers.user_id', auth()->user()->id)
->get('categories.type');
$category = Category::where('user_id', auth()->user()->id)->get();
return view('ledger.entries', compact('ledger', 'categories', 'ledgerCatType'))->render();
}
}
script
$(document).ready(function () {
$('.pagination a').on('click', function(event) {
event.preventDefault();
var page = $(this).attr('href').split('page=')[1];
fetch(page);
})
function fetch(page) {
$.ajax({
url : '/ledger/fetch?page='+page,
success : function(data)
{
$('#ledger-entry').html(data);
},
error : function(){
alert("error!!!!");
}
});
}
});
under the folder ledgers which will be called in the index.blade.php
entries.blade.php
<div class="outer-cont">
<table class="table container inner-cont">
<thead>
<th scope="col">Date</th>
<th scope="col">Description</th>
<th scope="col">Category</th>
<th scope="col">Amount</th>
<th scope="col"></th>
</thead>
<tbody>
#for($i = 0; $i < count($ledgers); $i++)
<tr scope="row">
<td class="tbl-date">{{ $ledgers[$i]->month }} {{ $ledgers[$i]->day }}, {{ $ledgers[$i]->year }}</td>
<td class="tbl-desc">{{ $ledgers[$i]->description }} </td>
<td>{{ $ledgers[$i]->category}} </td>
#if($ledgerCatType[$i]->type == "Expense")
<td class="tbl-amount" style="color: #FF5349;">Php ({{ $ledgers[$i]->amount }})</td>
#else
<td class="tbl-amount" style="color: #3BC23E;">Php {{ $ledgers[$i]->amount }}</td>
#endif
</tr>
#endfor
</table>
</div>
<div class="pagination">{!! $ledgers->links() !!}</div>
index.blade.php
<div id="ledger-entry">
#include('ledgers.entries')
</div>
web.php
Route::resource('ledger','LedgerController')->middleware('auth');
Route::get('/ledger/fetch', 'LedgerController#fetch')->middleware('auth');
Okay nevermind, I fixed it. I'm just going to post the answer here in case anyone gets stuck with it too.
The problem was my route, instead of using the resource I manually added the routes:
Route::get('ledger', 'LedgerController#index')->name('ledger.index')->middleware('auth');
Route::post('/ledger', 'LedgerController#store')->name('ledger.store')->middleware('auth');
Route::delete('/ledger/{id}', 'LedgerController#destroy')->name('ledger.destroy')->middleware('auth');
Route::get('/ledger/fetch', 'LedgerController#index')->name('ledger.fetch')->middleware('auth');
I also edited my code for the index() and thus combining it with the fetch() method thus it now looks like this:
public function index(Request $request)
{
$disableLedger = true;
$ledgers = Ledger::orderBy('id', 'DESC')
->where('user_id', auth()->user()->id)
->paginate(10);
$ledgerCatType = DB::table('ledgers')
->orderBy('ledgers.id', 'DESC')
->join('categories', 'ledgers.cat_id', '=', 'categories.id')
->where('ledgers.user_id', auth()->user()->id)
->select('categories.type')
->paginate(10);
$categories = Category::where('user_id', auth()->user()->id)->get();
if ($request->ajax())
{
return view('ledgers.entries', compact('ledgers', 'categories', 'ledgerCatType', 'disableLedger'))->render();
}
return view('ledgers.index', compact('ledgers', 'categories', 'ledgerCatType', 'disableLedger'));
}
I have search form to list properties/ads through certain criteria. In my form I am trying to search and list properties from database that correspond to entered min_price and max_price. When I submit form I get no results in table and when I die and dump min_price or max_price variable I get false. Any help is appreciated. Here is my code
CategoryController.php
<?php
namespace App\Http\Controllers;
use App\Category;
use App\Property;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
class CategoryController extends Controller
{
public function index()
{
return view('categories.search', compact('data'));
}
public function search($price, Request $request, Property $property)
{
$category = $property->category;
$query = Property::query();
// Code for min and max price
$min_price = $request->has('min_price');
$max_price = $request->has('max_price');
//dd($max_price);
if (($min_price) && ($max_price)) {
$query->whereBetween('price', [$min_price, $max_price]);
}
elseif (! is_null($min_price)) {
$query->where('price', '>=', $min_price);
}
elseif (! is_null($max_price)) {
$query->where('price', '<=', $max_price);
}
$results = $query->get();
return view('categories.search', compact('category', 'results'));
}
}
search.blade.php
#if(isset($results))
<table class="table">
<thead>
<th>Price</th>
</thead>
<tbody>
#foreach ($results as $result)
<tr>
<td>{{ $result->price }}</td>
</tr>
#endforeach
</tbody>
</table>
#endif
<form id="searchForm" method="GET" action="/search">
<div class="col-md-6 mb-6">
<label>Price</label>
<input type="number" id="min_price" name="min_price" class="form-control" placeholder="Min Price">
<input type="number" id="max_price" name="max_price" class="form-control" placeholder="Max Price">
</div>
<button class="btn btn-primary btn-lg btn-block">Search</button>
</form>
Main problem was is because you didn't have data in $request but in your variable $price you had something like this: "min_price=1000-max_price=2000".
So you need to get values from that string:
public function search($price, Request $request, Property $property)
{
$category = $property->category;
$array = explode('-', $price); // Array of your values
foreach($array as $a){
$s = [];
$s = explode('=', $a);
if ($s[0] === 'min_price'){
$s[1] ? $min_price = intval($s[1]) : $min_price = null;
} else {
$s[1] ? $max_price = intval($s[1]) : $max_price = null;
}
}
if (!empty($min_price) && !empty($max_price)) {
$results = Property::whereBetween('price', [$min_price, $max_price])->get();
return view('categories.search', compact('category', 'results'));
}
elseif (!empty($min_price)) {
$results = Property::where('price', '>=', $min_price)->get();
}
elseif (!empty($max_price)) {
$results = Property::where('price', '<=', $max_price)->get();
}
return view('categories.search', compact('category', 'results'));
}
Maybe you need to try to send min_price and max_price in better format, but this should work.
Good luck.
You can use laravel elqouent when method do do this.
So your query should look something like the following
$query = Property::query();
$request->has('max_price') && $request->has('min_price')
? $query->whereBetween('price', [$request->get('min_price'), $request->get('max_price')])
: $query->when($request->has('min_price'), function ($query) use ($request) {
$query->where('price', '>=', $request->get('min_price'));
})->when($request->has('min_price'), function ($query) use ($request) {
$query->where('price', '<=', $request->get('max_price'));
});
$results = $query->get();
Have a look at this https://laraveldaily.com/less-know-way-conditional-queries/ for more details
Good Luck
$request->has is a laravel function just to check if your request has certain value or not it will always return true or false.While to get request value you can use $request->get('name') so your search function should be:
public function search($price, Request $request, Property $property)
{
$category = $property->category;
$query = Property::query();
// Code for min and max price
$min_price= 0;
$max_price= 0;
if($request->has('min_price')){
$min_price = $request->get('min_price');
}
if($request->has('max_price')){
$max_price = $request->get('max_price');
}
//dd($max_price);
if (($min_price) && ($max_price)) {
$query->whereBetween('price', [$min_price, $max_price]);
}
elseif (! is_null($min_price)) {
$query->where('price', '>=', $min_price);
}
elseif (! is_null($max_price)) {
$query->where('price', '<=', $max_price);
}
$results = $query->get();
return view('categories.search', compact('category', 'results'));
}
}
I am having a hard time to get over this. Try to display a a single item by ID from database. I set the controller and route, but couldn't make it. Getting error or getting no data by the changes that I make on my show.blade
This is my whole controller:
public function welcome()
{
$estates = array();//here
$data['estates'] = $estates;
return view('welcome', $data);
}
public function search(Request $request)
{
$q = $request->q;
$estates = \DB::table('allestates')
->where("building_name", "LIKE", "%" . $q . "%")
->orWhere("address", "LIKE", "%" . $q . "%")
->orWhere("company_name", "LIKE", "%" . $q . "%")
->orWhere("region", "LIKE", "%" . $q . "%")
->orderBy('price')->paginate(10);
return view("search", compact('estates', 'q'));
}
public function show(allestates $allestates)
{
$estates = allestates::where('id', $allestates->id)->first();
//dd($estates);
if($estates){
return view('pages.show', ['estates' => $estates]);
}else{
return 'no records found';
}
}
Show function must be the problem, but what is the problem I couldn't figure it out.
This is the route:
Route::get("/", "PagesController#welcome");
Route::any("/search", "PagesController#search")->name('search.route');
Route::get('pages/{id}', 'PagesController#show');
And this is the show.blade.
<tbody>
<tr class="even">
<td>{{$estates->building_name}}</td>
</tr>
</tbody>
An this is the main.blade:
#foreach($estates as $estate)
<tr class="even">
<td>{{str_limit($estate->company_name, $limit = 20)}}</td>
<td>{{str_limit($estate->building_name, $limit = 20)}}</td>
<td>{{str_limit($estate->address, $limit = 22)}}</td>
<td>{{str_limit($estate->price, $limit = 20)}}</td>
<td class="price-hidden">{{$estate->old_price}}</td>
<td>{{str_limit($estate->extend, $limit = 20)}}</td>
<td>{{str_limit($estate->rooms, $limit = 20)}}</td>
<td>{{str_limit($estate->entry, $limit = 20)}}</td>
</tr>
#endforeach
ID returning null. but there is ID!
it's because laravel didn't find any record matching your query.
try using findOrFail in querying single record. this would return an error if no record is found.
$estates = allestates::findOrFail($id);
another way is to check wether the query is successful:
public function show($id)
{
$estates = allestates::where('id', $id)->first();
if($estates){
return view('pages.show', ['estates' => $estates]);
}else{
return 'no records found';
}
}
EXPLANATION
the $id paramater inside public function show($id) uses the {id} parameter in your route Route::get('pages/{id}', 'PagesController#show');
laravel will search the database based on the id you place in yoursite.com/pages/{id}
How can I delete or edit things from my database in Laravel 5.0 with the public function destroy and edit?
This is my library, here I want to delete or update something from my database
#foreach ($allJobs as $job)
<tr>
<td><img src="{{$job->selected_icon}}" width="50" /> </td>
<td>{{$job->jobtitle_de}}</td>
<td>{{$job->location}}</td>
<td><img src="{{$job->selected_image}}" width="100" /></td>
<td>{{$job->workinghours}}</td>
<td>{{$job->grey_header_de}}</td>
<td>{{$job->date}}</td>
<td>
<button>Edit</button> <a href="/delete">
<button>Delete</button></a></td>
<!--<td> <button type="delete" name="button"></button>-->
<td>
</td>
</tr>
#endforeach
In your controller (I will assume that you have created), implements this two functions.
public function edit($id) {
// Create a var called `$job` and uses the function `find()` passing into the $id that you clicked before
$job = Job::find($id);
// Return a view with the object that you found into a edit view
return view('jobs.edit', [
'job' => $job
]);
}
public function destroy($id) {
// Use the function `find()` passing into the $id that you clicked before and that use the delete method to delete the job
Job::find($id)->delete();
// Returning into a route that contains the jobs, probably
return redirect()->route('jobs');
}
Read the docs https://laravel.com/docs/5.4/controllers
in your route:
Route::post('delete','CallyourController#delete');
Route::post('update','CallyourController#update');
I think this is what you want to do.
my Controller:
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Request;
use App\Jobs;
class JobController extends Controller {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
return view('library',['allJobs' => Jobs::all()]);
}
//my create function
public function create()
{
return view('add');
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store(Request $request)
{
$job = new Jobs();
$job->jobtitle_de = array_key_exists('jobtitle_de',$_POST) ?
$_POST['jobtitle_de'] : '';
$job->jobtitle_en = array_key_exists('jobtitle_en',$_POST) ?
$_POST['jobt'] : '';
if (array_key_exists('place', $_POST)) {
$places = $_POST['place'];
$placesString = "";
foreach ($places as $p) {
$placesString .= $p.',';
}
$job->location = $placesString;
}
$job->workinghours = array_key_exists('workinghours',$_POST) ?
$_POST['workinghours'] : '';
$job->workinghours_de = array_key_exists('workinghours',$_POST) ?
$_POST['workinghours'] : '';
$job->selected_image= array_key_exists('selected_image',$_POST) ?
$_POST['selected_image'] : '';
$job->grey_header_de = array_key_exists('grey_header_de',$_POST) ?
$_POST['grey_header_de'] : '';
$job->selected_icon = array_key_exists('selected_icon',$_POST) ?
$_POST['selected_icon'] : '';
$job->selected_icon = array_key_exists('selected_icon',$_POST) ?
$_POST['selected_icon'] : '';
$job->selected_icon = array_key_exists('selected_icon',$_POST) ?
$_POST['selected_icon'] : '';
$job->selected_icon = array_key_exists('selected_icon',$_POST) ?
$_POST['selected_icon'] : '';
$job->date;
if (array_key_exists('date',$_POST) && !empty($_POST['date'])) {
$date = $_POST['date'];
$date = explode('/',$_POST['date']);
$newdate = $date[2]."-".$date[0]."-".$date[1];
$job->date = $newdate;
}
$job->grey_header_de = $_POST['grey_header_de'];
if (array_key_exists('workinghours',$_POST) && $_POST['workinghours']
=== "full-time") {
$job->workinghours = $_POST['workinghours'];
$job->workinghours_de = "Vollzeit";
}
if (array_key_exists('workinghours',$_POST) && $_POST['workinghours']
=== "part-time"){
$job->workinghours = $_POST['workinghours'];
$job->workinghours_de = "Teilzeit";
}
try {
$job->save();
}
catch (Exceptions $e) {
echo $e->getMessage();
}
return redirect()->action('JobController#index');
}
//my edit function
public function edit($id)
{
$job = Job::find($id);
return view('jobs.edit', [
'job' => $job
]);
}
//destroy function
public function destroy($id)
{
Job::find($id)->delete();
return redirect()->route('jobs');
}
now I found this in the internet:
<div class="library">
<table>
#foreach ($allJobs as $job)
<tr>
<td><img src="{{$job->selected_icon}}" width="50" /> </td>
<td>{{$job->jobtitle_de}}</td>
<td>{{$job->location}}</td>
<td><img src="{{$job->selected_image}}" width="100" /></td>
<td>{{$job->workinghours}}</td>
<td>{{$job->grey_header_de}}</td>
<td>{{$job->date}}</td>
<td>
{{ Form::open(['method' => 'DELETE', 'route' => 'job.destroy', $job]-
>id]) }}
{{ Form::hidden('id', $job-id) }}
{{ Form::submit('delete', ['class' => 'library']) }}
{{Form::close}}
</td>
</tr>
#endforeach
and this is my Controller
public function destroy($id)
{
$jobs = Job::findOrFail($id);
$jobs->delte();
return redirect::route('/');
}