BadMethodCallException Call to undefined method App\Models\BatterFirst::index() [closed] - laravel-8

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 1 year ago.
Improve this question
I want to add some data but I got
BadMethodCallException
Call to undefined method App\Models\BatterFirst::index()
error
where my model BatterFirst.php is
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class BatterFirst extends Model
{
use HasFactory;
protected $fillable = [
'name', 'runs', 'balls', 'sixs', 'fours'
];
}
This is my controller BatterFirstController.php
<?php
namespace App\Http\Controllers;
use App\Models\BatterFirst;
use Illuminate\Http\Request;
class BatterFirstController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$data = BatterFirst::latest()->paginate(5);
return view('BatterFirst.index',compact('data'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('BatterFirst.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'runs' => 'required',
'balls' => 'required',
'sixs' => 'required',
'fours' => 'required',
]);
BatterFirst::create($request->all());
return redirect()->route('BatterFirst.index')
->with('success','Batter created successfully.');
}
/**
* Display the specified resource.
*
* #param \App\Models\BatterFirst $batterFirst
* #return \Illuminate\Http\Response
*/
public function show(BatterFirst $batterFirst)
{
return view('BatterFirst.show',compact('BatterFirst'));
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Models\BatterFirst $batterFirst
* #return \Illuminate\Http\Response
*/
public function edit(BatterFirst $batterFirst)
{
return view('BatterFirst.edit',compact('BatterFirst'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Models\BatterFirst $batterFirst
* #return \Illuminate\Http\Response
*/
public function update(Request $request, BatterFirst $batterFirst)
{
$request->validate([
'name' => 'required',
'runs' => 'required',
'balls' => 'required',
'sixs' => 'required',
'fours' => 'required',
]);
$batterFirst->update($request->all());
return redirect()->route('BatterFirst.index')
->with('success','Batter updated successfully');
}
/**
* Remove the specified resource from storage.
*
* #param \App\Models\BatterFirst $batterFirst
* #return \Illuminate\Http\Response
*/
public function destroy(BatterFirst $batterFirst)
{
$batterFirst->delete();
return redirect()->route('BatterFirst.index')
->with('success','Batter deleted successfully');
}
}
This is my web.php
<?php
use App\Models\BatterFirst;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::resource('BatterFirst', BatterFirst::class);
This is my BatterFrist/index.php
#extends('BatterFirst.layout')
#section('content')
<div class="row" style="margin-top: 5rem;">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Laravel 8 CRUD Example from scratch - laravelcode.com</h2>
</div>
<div class="pull-right">
<a class="btn btn-success" href="{{ route('BatterFirst.create') }}"> Create New Post</a>
</div>
</div>
</div>
#if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
#endif
<table class="table table-bordered">
<tr>
<th>No</th>
<th>Name</th>
<th>Runs</th>
<th>Balls</th>
<th>Sixs</th>
<th>Fours</th>
<th>Strick Rate</th>
</tr>
#foreach ($data as $key => $value)
<tr>
<td>{{ ++$i }}</td>
<td>{{ $value->name }}</td>
<td>{{ $value->runs }}</td>
<td>{{ $value->overs }}</td>
<td>{{ $value->balls }}</td>
<td>{{ $value->sixs }}</td>
<td>{{ $value->fours }}</td>
{{-- <td>{{ $value->runs/$value->balls*100 }}</td> --}}
<td>#if ($value->runs > 0 and $value->runs ==0)
{{ $value->runs*100 }}
#elseif ($value->balls>0 and $value->runs ==0)
{{ $value->balls*$value->runs }}
#elseif ($value->balls==0 and $value->runs ==0)
{{ $value->balls * $value->runs }}
#elseif ($value->runs>0 and $value->balls>=0)
{{ $value->runs/$value->balls*100 }}
#endif
</td>
<td>
<form action="{{ route('BatterFirst.destroy',$value->id) }}" method="POST">
<a class="btn btn-info" href="{{ route('BatterFirst.show',$value->id) }}">Show</a>
<a class="btn btn-primary" href="{{ route('BatterFirst.edit',$value->id) }}">Edit</a>
#csrf
#method('DELETE')
<button type="submit" class="btn btn-danger">Delete</button>
</form>
</td>
</tr>
#endforeach
</table>
{!! $data->links() !!}
#endsection
What is the problem here? Thanks for helping me.
If you need anything more like more detailed code then ask me I will update it.
Note: I am just a beginner at laravel

You have to use the controller in web.php not model
use App\Http\Controllers\BatterFirstController;
Route::resource('BatterFirst', [BatterFirstController::class]);
Now you can call from any where e.g
In example.blade.php file
<a href={{'BatterFirst.index'}}>Index<a/>

Let's debug your code, starting where a request comes in to the application - at the routes file:
Route::resource('BatterFirst', BatterFirst::class);
You have a resource() route handled by BatterFirst::class. But where is that class? It has to map to something, and if you look at the top of that same routes file we see:
use App\Models\BatterFirst;
So a request for yoursite.com/BatterFirst/ will be handled by the index() method in your BatterFirst model. But of course there is no such method.
Stepping back, it is obvious you want the Controller to handle your routes, not your Model. Remove that use line at the top of your routes file, and replace it with:
use App\Http\Controllers\BatterFirstController;
And update your routes to be handled by that controller:
Route::resource('BatterFirst', BatterFirstController::class);

Related

Laravel 8 make 2 relationship between the same model

So, this is my relationship method on file model:
public function User()
{
return $this->belongsTo(
User::class,
'user_id',
'id'
);
}
public function modify()
{
return $this->belongsTo(
User::class,
'update_id',
'id'
);
}
This is my model table
This is my model migration code
public function up()
{
Schema::create('files', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->cascadeOnUpdate()->cascadeOnDelete();
$table->foreignId('update_id')->nullable()->references('id')->on('users');
$table->foreignId('division_id')->constrained()->cascadeOnUpdate();
$table->string('title');
$table->string('slug')->unique();
$table->text('details');
$table->timestamp('published_at')->nullable();
$table->timestamps();
});
}
This is my view code:
#foreach ($files as $key=>$file)
<tr>
<td>{{ $files->firstItem() + $key }}</td>
<td>{{ $file->title }}</td>
<td>{{ $file->division->name }}</td>
<td>
#if (auth()->user()->id == 1)
{{ $file->user->name }}
#else
{{ $file->user->name }}
#endif
</td>
<td>{{ $file->created_at }}</td>
<td>
{{-- #foreach ($file->modify as $update) --}}
{{ dd($file->modify->name) }}
This is my page view look like after executing code above
after change this line:
{{ dd($file->modify->name) }}
to:
{{ ($file->modify->name) }}
i got the following error:
ErrorException
Trying to get property 'name' of non-object
It would seem like the first $file in you array has the modify relationship set but there's a subsequent $file that's missing it. Either do a null check or make sure that the relationship is always set.

upload excel file for specific user in laravel-8 General error: 1364 Field 'user_id' doesn't have a default value

The idea is
a user have many data but all data belongsto one user
i am fasing SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into projects (name, detail, color, image, logo, updated_at, created_at) values (shahed, kjfs, fsdkf, fdsfsd, fds, 2021-05-30 08:45:35, 2021-05-30 08:45:35)) error.
If you neen more detail you can ask
This is my model project.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
use HasFactory;
protected $fillable = [
'name', 'detail', 'image','color','logo','user_id'
];
public function getUser(){
return $this->belongsTo(User::class);
}
}
This is model user.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Fortify\TwoFactorAuthenticatable;
use Laravel\Jetstream\HasProfilePhoto;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens;
use HasFactory;
use HasProfilePhoto;
use Notifiable;
use TwoFactorAuthenticatable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
public function getProducts(){
return $this->hasMany('App\Models\Product');
}
public function getProject(){
return $this->hasMany('App\Models\Project');
}
// public function products(){
// return $this->hasMany(Product::class);
// }
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
'two_factor_recovery_codes',
'two_factor_secret',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* The accessors to append to the model's array form.
*
* #var array
*/
protected $appends = [
'profile_photo_url',
];
}
This is project table projecttable.php
public function up()
{
Schema::create('projects', function (Blueprint $table) {
// $table->('id');
$table->bigIncrements('id');
$table->string('name', 255)->nullable();
$table->string('detail', 500)->nullable();
$table->string('color', 255)->nullable();
$table->decimal('image', 22)->nullable();
$table->decimal('logo', 22)->nullable();
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->nullable();
});
}
This is importProject.php
public function model(array $row)
{
return new Project([
'name' => $row['name'],
'detail' => $row['detail'],
'color' => $row['color'],
'image' => $row['image'],
'logo' => $row['logo'],
]);
}
This is projectController.php
<?php
namespace App\Http\Controllers;
use App\Exports\UsersExport;
use App\Models\Project;
use App\Imports\ProjectsImport;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class ProjectController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$projects = Project::where('user_id',auth()->user()->id)->latest()->paginate(20);
// $projects = Project::paginate(20);
return view('projects.index', compact('projects'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('projects.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'detail' => 'required',
'color' => 'required',
'image' => 'required',
'logo' => 'required',
]);
$input = $request->all();
$input['user_id'] = auth()->user()->id;
Project::create($input);
return redirect()->route('project.index')
->with('success','Product created successfully.');
}
/**
* Display the specified resource.
*
* #param \App\Models\Project $project
* #return \Illuminate\Http\Response
*/
public function show(Project $project)
{
return view('projects.show', compact('project'));
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Models\Project $project
* #return \Illuminate\Http\Response
*/
public function edit(Project $project)
{
return view('projects.edit', compact('project'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Models\Project $project
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Project $project)
{
$user_id = Auth::user()->id ;
$request->validate([
'name' => 'required',
'detail' => 'required',
'color' => 'required',
'image' => 'required',
'logo' => 'required'
]);
$input = $request->all();
$project->update($input);
return redirect()->route('project.index')
->with('success','Product updated successfully');
}
/**
* Remove the specified resource from storage.
*
* #param \App\Models\Project $project
* #return \Illuminate\Http\Response
*/
public function destroy(Project $project)
{
$project->delete();
return redirect()->route('projects.index')
->with('success', 'Project deleted successfully');
}
public function importProject()
{
Excel::import(new ProjectsImport, request()->file('file'));
return back()->with('success','Project created successfully.');
}
public function export()
{
return Excel::download(new UsersExport, 'projects.xlsx');
}
}
this is index.blade.php
#extends('layouts.app')
#section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Laravel 8 CRUD </h2>
</div>
<div class="d-flex flex-row-reverse flex-column">
<div class="d-flex">
<a class="btn btn-success text-light mr-5" data-toggle="medel" id="mediumButton" data-target="#mediumModel"
data-attr="{{ route ('projects.create')}}" title="upload project">
<i class="fas fa-cloud-upload-alt fa-2x"></i>
</a>
<form action="{{ route('importProject') }}" method="POST" enctype="multipart/form-data" class="d-flex">
#csrf
<input type='file' name="file">
<button class="btn btn-info" style="margin-left: -60px" title="Import Project">
<i class="fas fa-cloud-upload-alt fa-2x"></i></button>
<a class="btn btn-warning" href="{{ route('export') }}">Export User Data</a>
</form>
</div>
</div>
<div class="pull-right">
<a class="btn btn-success text-light" data-toggle="modal" id="mediumButton" data-target="#mediumModal"
data-attr="{{ route('projects.create') }}" title="Create a project"> <i class="fas fa-plus-circle"></i>
</a>
</div>
</div>
</div>
#if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
#endif
<table class="table table-bordered table-responsive-lg table-hover">
<thead class="thead-dark">
<tr>
<th scope="col">No</th>
<th scope="col">Name</th>
<th scope="col" width="30%">Details</th>
<th scope="col">color</th>
<th scope="col">image</th>
<th scope="col">logo</th>
<th scope="col">Date Created</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
#foreach ($projects as $project)
<tr>
<td scope="row">{{ ++$i }}</td>
<td>{{ $project->name }}</td>
<td>{{ $project->detail }}</td>
<td>{{ $project->color }}</td>
<td>{{ $project->image }}</td>
<td>{{ $project->logo }}</td>
<td>{{ date_format($project->created_at, 'jS M Y') }}</td>
<td>
<form action="{{ route('projects.destroy', $project->id) }}" method="POST">
<a data-toggle="modal" id="smallButton" data-target="#smallModal"
data-attr="{{ route('projects.show', $project->id) }}" title="show">
<i class="fas fa-eye text-success fa-lg"></i>
</a>
<a class="text-secondary" data-toggle="modal" id="mediumButton" data-target="#mediumModal"
data-attr="{{ route('projects.edit', $project->id) }}">
<i class="fas fa-edit text-gray-300"></i>
</a>
#csrf
#method('DELETE')
<button type="submit" title="delete" style="border: none; background-color:transparent;">
<i class="fas fa-trash fa-lg text-danger"></i>
</button>
</form>
</td>
</tr>
#endforeach
</tbody>
</table>
{!! $projects->links() !!}
<!-- small modal -->
<div class="modal fade" id="smallModal" tabindex="-1" role="dialog" aria-labelledby="smallModalLabel"
aria-hidden="true">
<div class="modal-dialog modal-sm" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="smallBody">
<div>
<!-- the result to be displayed apply here -->
</div>
</div>
</div>
</div>
</div>
<!-- medium modal -->
<div class="modal fade" id="mediumModal" tabindex="-1" role="dialog" aria-labelledby="mediumModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="mediumBody">
<div>
<!-- the result to be displayed apply here -->
</div>
</div>
</div>
</div>
</div>
<script>
// display a modal (small modal)
$(document).on('click', '#smallButton', function(event) {
event.preventDefault();
let href = $(this).attr('data-attr');
$.ajax({
url: href,
beforeSend: function() {
$('#loader').show();
},
// return the result
success: function(result) {
$('#smallModal').modal("show");
$('#smallBody').html(result).show();
},
complete: function() {
$('#loader').hide();
},
error: function(jqXHR, testStatus, error) {
console.log(error);
alert("Page " + href + " cannot open. Error:" + error);
$('#loader').hide();
},
timeout: 8000
})
});
// display a modal (medium modal)
$(document).on('click', '#mediumButton', function(event) {
event.preventDefault();
let href = $(this).attr('data-attr');
$.ajax({
url: href,
beforeSend: function() {
$('#loader').show();
},
// return the result
success: function(result) {
$('#mediumModal').modal("show");
$('#mediumBody').html(result).show();
},
complete: function() {
$('#loader').hide();
},
error: function(jqXHR, testStatus, error) {
console.log(error);
alert("Page " + href + " cannot open. Error:" + error);
$('#loader').hide();
},
timeout: 8000
})
});
</script>
#endsection
Give auth value in import project like this :)
public function model(array $row)
{
return new Project([
'name' => $row['name'],
'detail' => $row['detail'],
'color' => $row['color'],
'image' => $row['image'],
'logo' => $row['logo'],
'user_id' => auth()->user()->id
]);
}

Route [aktivitas.destroy] not defined. (View: C:\xampp\htdocs\TA\resources\views\aktivitas\index.blade.php)

I Try Made Crud Can't defined aktivitas.destroy
index.blade.php
<div class="bs-bars pull-left">
<a href="{{ route('pegawai.create') }}"class="btn btn-primary btn-md">
Tambah
</a>
<a href="{{ url('pegawai-pdf') }}" class="btn btn-success btn-md">
<i class="fas fa-file-pdf"></i> Data Aktivitas
</a>
</div>
#foreach($ar_judul as $jdl)
<th>{{ $jdl }}</th>
#endforeach
</tr>
</thead>
<tbody>
#foreach ($ar_aktivitas as $akt)
<tr>
<td>{{ $no++ }}</td>
<td>{{ $akt->nama_jenis_anggaran }}</td>
<td>{{ $akt->jenis_anggaran }}</td>
<td>{{ $akt->unt }}</td>
<td>Rp. {{ number_format($akt->jumlah_anggaran,2,',','.') }}</td>
<td>{{ $akt->peg }}</td>
<td>{{ $akt->tgl_aktivitas }}</td>
<td>
#if(!empty($akt->foto))
<img src="{{asset('img')}}/{{ $akt->foto }}" width="70px" height="70px">
#else
<div class="icon text-black bg-violet">
<i class="fas fa-tired"></i>
</div>
#endif
</td>
<td>
<form method="POST" action="{{ route('aktivitas.destroy',$akt->id)}}">
<div class="icon">
<a href="{{ route('aktivitas.show',$akt->id) }}" >
<div class="icon bg-blue">
<i class="fas fa-eye"></i>
</div>
</a>
<a href="{{ route('aktivitas.edit',$akt->id) }}" class="">
<div class="icon bg-green">
<i class="fas fa-pen"></i>
</div>
</a>
#csrf
#method('DELETE')
<button type="submit"
class="btn-danger btn-circle btn-sm"
onclick="return confirm('Yakin diHapus?')">
<div class="icon bg-red">
<i class="fas circle fa-trash"></i>
</div>
</button>
AktivitasController.php Controller
class AktivitasController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$ar_aktivitas = DB::table('aktivitas')
->join('unit', 'unit.id', '=', 'aktivitas.unit_id')
->join('pegawai', 'pegawai.id', '=', 'aktivitas.pegawai_id')
->select('aktivitas.*', 'unit.nama AS unt', 'pegawai.nama AS peg')
->get();
return view('aktivitas.index', compact('ar_aktivitas'));
}
public function create()
{
//arahkan ke form input data baru
return view('aktivitas.form');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//validasi data
$validator = Validator::make(request()->all(),[
'nama_jenis_anggaran'=>'required',
'jenis_anggaran'=>'required',
'unit_id'=>'required',
'jumlah_anggaran'=>'required',
'pegawai_id'=>'required',
'tgl_aktivitas'=>'required',
'keterangan'=>'image|mimes:jpg,jpeg,png,gif|max:2048',
],[
'nama_jenis_anggaran.required'=>'Nama Jenis Anggaran Wajib untuk diisi',
'jenis_anggaran.required'=>'Jenis Anggaran Wajib untuk dipilih',
'unit_id.required'=>'Unit Wajib untuk dipilih',
'jumlah_anggaran.required'=>'Jumlah Anggaran Wajib untuk dipilih',
'pegawai.required'=>'Pegawai Wajib untuk diisi',
'tgl_aktivitas.required'=>'Tanggal Wajib untuk diisi',
'keterangan.image'=>'Ektensi File Foto Hanya Boleh .jpg, .png, .gif',
'keterangan.max' =>'File Foto Melebihi 2048 KB',
])->validate();
//2. proses upload,dicek pas input ada upload file/tidak
if(!empty($request->foto)){
/*
$request->validate([
'foto' => 'image|mimes:jpg,jpeg,png,giff|max:2048',
]);
*/
//$fileName = $request->nip.'.'.$request->foto->extension();
$fileName = $request->nip.'.jpg';
$request->foto->move(public_path('img'), $fileName);
}else{
$fileName = '';
}
//1. tangkap request form
DB::table('aktivitas')->insert(
[
'pegawai_id'=>$request->pegawai_id,
'nama_jenis_anggaran'=>$request->nama_jenis_anggaran,
'jenis_anggaran'=>$request->jenis_anggaran,
'jumlah_anggaran'=>$request->jumlah_anggaran,
'tgl_aktivitas'=>$request->tgl_aktivitas,
'keterangan'=>$request->$fileName,
'unit_id'=>$request->unit_id,
]
);
//landing page
return redirect ('/aktivitas');
}
public function show($id)
{
$ar_aktivitas = DB::table('aktivitas')
->join('unit', 'unit.id', '=', 'aktivitas.unit_id')
->join('pegawai', 'pegawai.id', '=', 'aktivitas.pegawai_id')
->select('aktivitas.*', 'unit.nama AS unt', 'pegawai.nama AS peg')
->where('aktivitas.id','=',$id)
->get();
return view('aktivitas.index', compact('ar_aktivitas'));
}
public function edit($id)
{
//tampilkan form untuk menampilkan
//data lama yg mau diedit sebanyak 1 baris data
$data = DB::table('aktivitas')->where('id',$id)->get();
return view('aktivitas/form_edit',compact('data'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//1.proses ubah data
DB::table('aktivitas')->where('id',$id)->update(
[
'pegawai_id'=>$request->pegawai_id,
'nama_jenis_anggaran'=>$request->nama_jenis_anggaran,
'jenis_anggaran'=>$request->jenis_anggaran,
'jumlah_anggaran'=>$request->jumlah_anggaran,
'tgl_aktivitas'=>$request->tgl_aktivitas,
'keterangan'=>$request->keterangan,
'unit_id'=>$request->unit_id,
]
);
//landing page ke detail pemasukan
return redirect ('/activity'.'/'.$id);
}
public function destroy($id)
{
//ambil isi kolom foto lalu hapus file fotonya
//di folder img
//$foto = DB::table('aktivitas')->select('keterangan')->where('id','=',$id)->get();
//foreach($foto as $f){
// $namaFile = $f->foto;
//}
//File::delete(public_path('img/'.$namaFile));
///hapus data
DB::table('aktivitas')->where('id',$id)->delete();
//landing page ke hal pegawai / index.blade.php
return redirect ('/activity');
}
}
You can add:
Route::delete('aktivitas','AktivitasController#destroy');
Add on your routes/web.php

How to make pagination in laravel with vue component js and axios router-view

Now I have some problem that is to paginate all data stored in my Tasks table,
I have trying some code in ways to make pagination in laravel, but the code not work with .vue file extension.
I'm using laravel 5.8, vue.js, axios, and vue-router-view.
My code not working or its maybe wrong overall,
// this is my index function in my taskController file :
public function index(Request $request)
{
// return new taskCollection(Task::orderBy('created_at', 'desc')->paginate(5));
$tasks = Task::orderBy('created_at', 'desc')->paginate(10);
return response()->json($tasks)
->withCallback($request->callback);
}
// and this is my code to fetch the data from response given by controller:
methods: {
getTaskList() {
let uri = `/api/tasks`;
this.axios
.get(uri)
.then(response => {
if (!this.tasks.data) {
this.tasks = response.data.data;
} else {
this.tasks.data.push(...response.data.data);
this.tasks.next_page_url = response.data.next_page_url;
}
})
.catch(function(error) {
console.log(error);
});
},
//I want to paginate the data so it's not showing all data entire the page.
Refactor your code referring this.
First, install Laravel Vue pagination
npm install laravel-vue-pagination
in your APP.JS
Vue.component('pagination', require('laravel-vue-pagination'));
in your Controller
public function index(){
return User::latest()->paginate(5);
}
in your Vue file
<div class="card-body table-responsive p-0">
<table class="table table-hover">
<tbody>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Type</th>
<th>Registered At</th>
<th>Modify</th>
</tr>
<tr v-for="user in users.data" :key="user.id">
<td>{{user.id}}</td>
<td>{{user.name}}</td>
<td>{{user.email}}</td>
<td>{{user.type | upText}}</td>
<td>{{user.created_at | myDate}}</td>
<td>
<a href="#" #click="editModal(user)">
<i class="fa fa-edit blue"></i>
</a>
/
<a href="#" #click="deleteUser(user.id)">
<i class="fa fa-trash red"></i>
</a>
</td>
</tr>
</tbody></table>
</div>
<!-- /.card-body -->
<div class="card-footer">
<pagination :data="users" #pagination-change-page="getResults"></pagination>
</div>
</div>
In your Script
getResults(page = 1) {
axios.get('api/user?page=' + page)
.then(response => {
this.users = response.data;
});
},
in API route
Route::apiResources(['user' => 'API\UserController']);

Cant write data in database using codeigniter

I have a controller, model and view file. I am trying to write data to database using the form on view file. I am trying to validate the post data using a mix of Codeigniter Validation library and some methods defined by. This validation is being done in Controller. Then I am trying to pass data array to the model. In the model I am trying to read the data array and build a query to insert data in database.
The problem is that no data is being written in the database.
I dont see any visible errors in the browser. I have been stuck on this for some time now. Any help is appreciated. Thanks in advance.
Controller
function add_customer() {
$this->load->model('Customer_Model');
$data['title'] = "Add New Customer";
$this->load->view('templates/header' , $data);
$this->load->view('dashboard/add_customer' , $data);
$this->load->view('templates/footer' , $data);
if($this->input->post())
{
$this->form_validation->set_rules('name', 'Name', 'trim|required');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|customer_email_exists');
$this->form_validation->set_rules('mobile', 'Mobile', 'trim|required|customer_mobile_exists');
$this->form_validation->set_rules('address', 'Address', 'trim|required');
if ($this->form_validation->run()){
$customer_data = array(
'name' => $this->validation->name,
'email' => $this->validation->email,
'mobile' => $this->validation->mobile,
'address' => $this->validation->address
);
$this->Customer_Model->add_customer($customer_data);
}else{
}
}
}
public function customer_email_exists($email) {
$this->load->model('Customer_Model');
if(!$this->Customer_Model->email_exists($email)){
return true;
}else{
$this->form_validation->set_message('email_exists', 'Email already registered, try another one.');
return false;
}
}
public function customer_mobile_exists($mobile) {
$this->load->model('Customer_Model');
if(!$this->Customer_Model->mobile_exists($mobile)){
return true;
}else{
$this->form_validation->set_message('email_exists', 'Email already registered, try another one.');
return false;
}
}
}
Model
class Customer_Model extends CI_Model{
function add_customer($customer_data)
{
$data = array(
'id'=>'',
'name'=>$customer_data["name"],
'email'=>$customer_data["email"],
'mobile'=>$customer_data["mobile"],
'address'=>$customer_data["address"]
);
$this->db->insert('customer',$data);
$this->db->query($query);
}
public function email_exists($email) {
$this->db->where("email = '$email' AND email != ''");
$query = $this->db->get('customer');
if ($query->num_rows() > 0){
return true;
}else{
return false;
}
}
public function mobile_exists($mobile) {
$this->db->where('mobile',$mobile);
$query = $this->db->get('customer');
if ($query->num_rows() > 0){
return true;
}else{
return false;
}
}}
View
<section class="versir-section">
<div class="container">
<div class="row">
<div class="col-12">
<?php echo validation_errors(); ?>
<form method="post">
<table width="600" border="1" cellspacing="5" cellpadding="5">
<tr>
<td width="230">Customer Name</td>
<td width="329"><input type="text" name="name"/></td>
</tr>
<tr>
<td>Customer Email </td>
<td><input type="text" name="email"/></td>
</tr>
<tr>
<td>Customer Mobile </td>
<td><input type="text" name="mobile"/></td>
</tr>
<tr>
<td>Customer Address </td>
<td><input type="text" name="address"/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="save" value="Save Data"/></td>
</tr>
</table>
</form>
</div>
</div>
</div>
Hmm! I think in this code part you should get post data from input, not from validation
if ($this->form_validation->run()){
$customer_data = array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'mobile' => $this->input->post('mobile'),
'address' => $this->input->post('address'),
);
$this->Customer_Model->add_customer($customer_data);
}else{
}