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

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

Related

Model binding with multiple rows in ASP.NET Core MVC

I've been stuck on this for so long, any help or direction is appreciated.
Basically I want my controller to pass a json data like this:
Initially, I wanted to do it with model binding, but at this moment even jQuery will be fine.
Model class:
public class Orders
{
public int Id { get; set; }
public int CustomerId { get; set; }
public string ItemName { get; set; }
public double Price { get; set; }
public IEnumerable<SelectListItem> CustomersList { get; set; }
}
Controller code:
// GET: OrdersController/Create
public ActionResult Create()
{
var listCustomers = dbContext.Customers
.Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = x.DepName
});
var orders = new Orders()
{
CustomersList = listCustomers
};
//var orders = new List<Orders>();
return View(orders);
}
// POST: OrdersController/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(List<Orders> ordersList)
{
Orders newOrders = new Orders();
foreach (var order in ordersList)
{
newOrders.Id = 0;
newOrders.CustomerId = order.CustomerId;
newOrders.ItemName = order.ItemName;
newOrders.Price = order.Price;
}
// I will be processing newOrders into application/json and sending to the backend API
}
View markup:
#model List<NameSpace.Web.Models.Orders>
#{
ViewData["Title"] = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="row">
<div class="col-md-8">
<div class="form-group">
#Html.LabelFor(model => model.CustomerId, htmlAttributes: new { #class = "control-label col-md-6" })
#Html.DropDownListFor(model => model.CustomerId, Model.CustomersList, "Select Customer ", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.DepId, "", new { #class = "text-danger" })
</div>
</div>
<hr>
<div class="col-md-12">
<div class=''></div>
<thead>
<tr>
//<th style="width:150px">Cust. Id</th>
<th style="width:150px">Item Name</th>
<th style="width:150px">Price</th>
</tr>
</thead>
<tbody id="tblOrdersBody">
<tr>
//<td><input name='Orders[0].CustomerId' class="form-control" /></td>
<td><input name='Orders[0].ItemName' class="form-control" /></td>
<td><input name='Orders[0].Price' class="form-control" /></td>
</tr>
</tbody>
<tfooter>
<tr><a hre="#" class="btn btn-success" id="addOrder"></a> </tr>
</tfooter>
</table>
<div class="row">
<div class="tile-footer d-flex justify-content-around">
#Html.ActionLink("Cancel", "Index", null, new { #class = "btn btn-danger" })
<input id="btnSave" type="submit" value="Save Order" class="btn btn-primary" />
</div>
</div>
</div>
</div>
}
#section Scripts {
<script>
var i = 1;
$(document).on("click", "#addOrder", function () {
$("#tblOrdersBody").append("<tr>"
//+ "<td><input name='Orders[" + i + "].CustomerId' class='form-control' /></td>"
+ "<td><input name='Orders[" + i + "].ItemName' class='form-control'/></td>"
+ "<td><input name='Orders[" + i + "].Price' class='form-control'/></td>"
+ "<td><button type='button' class='btn btn-danger' id='btnRemove' </buuton></td>"
+ "</tr > ");
i++;
});
</script>
}
I have seen many similar questions , the closest one being this one, but I could figure it out, the controller receives 0 in item counts
public ActionResult Create(List ordersList)
You action parameter named ordersList, please try to modify the name attribute of your input(s) on view page, like below.
<tbody id="tblOrdersBody">
<tr>
<td><input name='ordersList[0].CustomerId' class="form-control" /></td>
<td><input name='ordersList[0].ItemName' class="form-control" /></td>
<td><input name='ordersList[0].Price' class="form-control" /></td>
</tr>
</tbody>
JS code
<script>
var i = 1;
$(document).on("click", "#addOrder", function () {
$("#tblOrdersBody").append("<tr>"
+ "<td><input name='ordersList[" + i + "].CustomerId' class='form-control' /></td>"
+ "<td><input name='ordersList[" + i + "].ItemName' class='form-control'/></td>"
+ "<td><input name='ordersList[" + i + "].Price' class='form-control'/></td>"
+ "<td><button type='button' class='btn btn-danger' id='btnRemove' </buuton></td>"
+ "</tr > ");
i++;
});
</script>
Test Result

while using Edit function in controller missing parameter error is showing up and when checked using dd {#connection: null #table: null }

i am trying to make a edit function for my subcategories while its show eerror like missing parament, dd showing connection null
the web.php in my routes
web.php
<?php
use App\Http\Controllers\SubCategoryController;
Route::resource('/subcategory', SubCategoryController::class);
the subcategorycontroller
controller
public function edit(subCategory $subCategory)
{
// dd($subCategory);
}
the subcategory model
model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class SubCategory extends Model
{
use HasFactory;
protected $fillable =['name'];
}
my migration file for subcategory
migration
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateSubCategoriesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('sub_categories', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->integer('category_id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('sub_categories');
}
}
the output for dd
output
App\Models\SubCategory {#1377 ▼
#fillable: array:1 [▶]
#connection: null
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
+preventsLazyLoading: false
#perPage: 15
+exists: false
+wasRecentlyCreated: false
#escapeWhenCastingToString: false
#attributes: []
#original: []
#changes: []
#casts: []
#classCastCache: []
#attributeCastCache: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▶]
}
the connection and table is showing null when its supposed to say mysql,subcategory
i am also providing the code where i did not used dd and done normaly and its error
controller
public function edit(subCategory $subCategories)
{
// dd($subCategories);
return view('subcategory/edit', compact('subCategories'));
}
the edit.blade.php file in my views
edit.blade
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-12">
<div class="card">
<div class="card-header">Edit Category</div>
<div class="card-body">
<form method="POST" action="{{ route('subcategory.update',[$subCategories->id]) }}">
#method('PUT')
#csrf
<div class="form-group row">
<label for="name" class="col-md-4 col-form-label text-md-right">{{ __('Name') }}</label>
<div class="col-md-6">
<input id="name" type="text" class="form-control #error('name') is-invalid #enderror" name="name" required autocomplete="name" autofocus>
#error('name')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Commit Changes') }}
</button>
<a class="btn btn-primary" href="{{route('subcategory.index')}}">{{ __('lang.Cancel') }}</a>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
and the output of missing parameter was obtained
output
Illuminate\Routing\Exceptions\UrlGenerationException
Missing required parameter for [Route: subcategory.update] [URI:
subcategory/{subcategory}] [Missing parameter: subcategory]. (View:
C:\xampp\htdocs\Exam\resources\views\subcategory\edit.blade.php)
http://127.0.0.1:8000/subcategory/1/edit
how can i solve this
changing the edit function in the controller fixed the problem
public function edit($id)
{
$subCategory = Subcategory::find($id);
return view('subcategory/edit', compact('subCategory'));
}

Route [news.shownewspublic] not defined

I want to view some data but I got this error Route [news.shownewspublic] not defined. (View: C:\xampp\htdocs\ContentBaseApp - 1.0.2\resources\views\news\indexnewspublic.blade.php)
This is my resources\views\news folder
This is resources\views\news\indexnewspublic.blade.php
#foreach ($news as $news)
<a class="btn btn-outline-info" href="{{route('news.shownewspublic'),$news->id}}">
<img src="/image/{{ $news->image }}" width="100px" class="col-2">
<div class="col-2" style="color: #1d2124">
<strong>App Name:- {{ $news->name }}</strong>
</div>
</a>
#endforeach
This is my NewsController.php
public function indexnewspublic()
{
$news = News::latest()->paginate(5);
return view('news.indexnewspublic',compact('news'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
public function shownewspublic(News $news)
{
return view('news.shownewspublic',compact('news'));
}
This is web.php
Route::resource('news', NewsController::class);
Route::get('/indexnewspublic', [NewsController::class, 'indexnewspublic']);
Route::get('/shownewspublic', [NewsController::class, 'shownewspublic']);
Solved by in indexnewspublic.php
#foreach ($news as $news) <a class="btn btn-outline-info" href="{{ url('shownewspublic/' . $news->id) }}"> {{ $news->name }} <img src="/image/{{ $news->image }}" width="100px" class="col-6"> </a> #endforeach
This is web.php
Route::get('indexnewspublic/{id}', [NewsController::class, 'indexnewspublic'])->name('indexnewspublic');
This is NewsController.php
public function indexnewspublic()
{
$news = News::latest()->paginate(5);
return view('news.indexnewspublic',compact('news'))
->with('i', (request()->input('page', 1) - 1) * 5);
}

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

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

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
]);
}