Hi im new in website develpoment and i have a problem in my project(laravel, vue.js, mysql), i created the delete api and it works well when i used postman but in the Vue file when use the axios.delete it did not work ?
btw (post,get) work well.
sorry for this english.
<template>
<div class="table">
<table>
<tr>
<th>Id</th>
<th>Matricule</th>
<th>Nom</th>
<th>Prenom</th>
<th>Email</th>
<th>Annee</th>
<th>Action</th>
</tr>
<tr v-for="etud in EtudTable" :key="etud.id">
<td>{{etud.id}}</td>
<td>{{etud.matricule}}</td>
<td>{{etud.nom}}</td>
<td>{{etud.prenom}}</td>
<td>{{etud.email}}</td>
<td>{{etud.annee}}</td>
<td><button #click.prevent="Delete(etud.id)">Supprimé</button></td>
</tr>
</table>
</div>
</template>
<script>
export default {
data(){
return {
EtudTable : []
}
} ,
created:{
},
methods:{
Delete(id) {
axios.delete('api/Etudiant/${id}').then(function (response){
let index = this.EtudTable.findIndex(etud => etud.id === id);
this.EtudTable.splice(index, 1);
});
},
getVueItems: function getVueItems() {
var _this = this;
axios.get('api/Etudiant').then(function (response) {
_this.EtudTable = response.data;
});
},
....
}
}
</script>
Route\api:
Route::delete('Etudiant/{id}', 'EtudiantController#Delete')->name('etudiant.delete');
EtudiantController.php:
<?php
namespace App\Http\Controllers;
use App\Etudiant;
use Illuminate\Http\Request;
class EtudiantController extends Controller
{
...
public function Delete($id){
$etudiant = Etudiant::find($id);
$etudiant->delete();
return response()->json('successfully deleted');
}
...
}
Etudiant model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Etudiant extends Model
{
protected $fillable = ['matricule', 'nom', 'prenom', 'email', 'annee'];
}
axios.delete(`api/Etudiant/${id}`).then(....)
Use backtick ` not '.
Reference link
Related
with laravel controller the app working without anz problem,like that:
UserController.php
public function user_list(Request $request)
{
if ($request->ajax()) {
$data = User::whereHas('roles')->get()->map(function($permission) {
return [
'id' => $permission->id,
'fullname' => $permission->name . ', ' . $permission->lastname,
];
});
return datatables()->of($data)->make(true);
}
$pageConfigs = ['pageHeader' => false];
return view('/content/apps/user/app-user-list', ['pageConfigs' => $pageConfigs]);
}
in my view :
<div class="card">
<div class="table-responsive">
<table class="users-table table">
<thead class="table-light">
<tr>
<th>id</th>
<th>Full Name</th>
</tr>
</thead>
</table>
</div>
</div>
#section('page-script')
<script>
$(function() {
$('.users-table').DataTable({
ajax: "list", // JSON file to add data
columns: [
// columns according to JSON
{ data: "id" },
{ data: "fullname" },
</script>
#endsection
and the route in Web.php is:
Route::get('users', [UsersController::class, 'user_list'])->name('list');
now when i want to use Livewire component instead of Laravel controller , where should i du my request in 'render' function or in 'mount' or schould i create another function, and how can i call if from route. or if there someway to call the function direct from controller without creating a new function on more time in Livewire component.
will be greate when someone can helpe
I really need a solution for this problem. I'm using Laravel 8.
I am trying to fetch nama (name) field from the kategoris (category) table and show it in the produks (product) table.
View Blade with JS code in the end
#extends('back.index')
#section('content')
<main>
<div class="container-fluid">
<h1 class="mt-4">Produk</h1>
<ol class="breadcrumb mb-4">
<li class="breadcrumb-item"><a href={{ route('home') }}>Dashboard</a></li>
<li class="breadcrumb-item active">Produk</li>
</ol>
<div class="card mb-4">
<div class="card-body">
DataTables is a third party plugin that is used to generate the demo table below. For more information about DataTables, please visit the
<a target="_blank" href="https://datatables.net/">official DataTables documentation</a>
.
</div>
</div>
<div class="card mb-4">
<div class="card-header">
<i class="fas fa-table mr-1"></i>
DataTable Example
#auth
Tambah Produk
#endauth
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered" id="produks-table" width="100%" cellspacing="0">
<thead>
<tr>
<th>Kode</th>
<th>Nama</th>
<th>Kategori</th>
<th>Updated At</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Kode</th>
<th>Nama</th>
<th>Kategori</th>
<th>Updated At</th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
</main>
#endsection
#push('scripts')
<script>
$(function() {
$('#produks-table').DataTable({
processing: true,
serverSide: true,
ajax: 'produk/json',
columns: [
{ data: 'kode', name: 'kode' },
{ data: 'nama', name: 'nama',
fnCreatedCell: function (nTd, sData, oData, iRow, iCol) {
$(nTd).html("<a href='/kategoris/"+oData.id+"'>"+oData.nama+"</a>");
}
},
{ data: 'kategori', name: 'kategori.nama'},
{ data: 'updated_at', name: 'updated_at'},
]
});
});
</script>
#endpush
I already look for solutions for several days, but I still get this error message.
Product Model
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Produk extends Model
{
use HasFactory;
protected $casts = [
'updated_at' => 'datetime:d/m/Y, H:i:s'
];
public function Produk()
{
return $this->belongsTo(Kategori::class, 'kategori_id');
}
}
Category Model
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Kategori extends Model
{
use HasFactory;
protected $casts = [
'updated_at' => 'datetime:d/m/Y, H:i:s'
];
public function Kategori()
{
return $this->hasMany(Produk::class);
}
}
Product Controller
namespace App\Http\Controllers;
use App\Models\Produk;
use Illuminate\Http\Request;
use RealRashid\SweetAlert\Facades\Alert;
use Yajra\Datatables\DataTables;
class ProdukController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function json()
{
return Datatables::of(Produk::with('Kategori')->get())->make(true);
}
public function index()
{
return view('back.produk.show');
}
}
I was wrong while naming model functions.
Category Model
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Kategori extends Model
{
use HasFactory;
protected $casts = [
'updated_at' => 'datetime:d/m/Y, H:i:s'
];
public function Produk() //Here
{
return $this->hasMany(Produk::class);
}
}
Product Model
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Produk extends Model
{
use HasFactory;
protected $casts = [
'updated_at' => 'datetime:d/m/Y, H:i:s'
];
public function Kategori() //Here
{
return $this->belongsTo(Kategori::class, 'kategori_id');
}
}
Im using v-for and axios for displaying data but when I run my website, the data wont show but there are no errors in the console and in my vue developer tool, I can see the data in it. Can someone help me?
Users.vue
<table id="table" class="table table-striped table-bordered">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Type</th>
<th>Created</th>
</tr>
</thead>
<tbody>
<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}}</td>
<td>{{user.created_at}}</td>
</tr>
</tbody>
</table>
script>
export default {
data() {
return {
users: {},
form: new Form({
id:'',
name: "",
email: "",
password: "",
type: "",
})
};
},
methods: {
loadUsers(){
axios.get("api/user").then(({ data }) => (this.users = data));
}
},
created() {
console.log('Component mounted.')
this.loadUsers()
}
}
</script>
api.php
Route::apiResource('user', 'API\UserController');
UserController.php
<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return User::all();
}
}
Try this...
<tr v-for="user in users" :key="user.id">
I have categories table and clubs table, relationship between is
A category has many clubs
1 category can have many clubs
1 club have 1 category
I want to show clubs based on category, which will be selected with dropdown list, so other clubs will be hided. See the Screenshot for more understanding
My Controller (I have no issues getting category names to dropdown list):
public function club()
{
$categories_name = Category::pluck('category_name','id');
$user_id = auth()->user()->id;
$user = User::find($user_id);
$data = array(
'user_clubs' => $user->clubs,
'categories_name' => $categories_name
);
return view('pages.dashboard.club_dashboard')->with($data);
}
My View
<div class="form-group">
<strong>{{Form::label('categories_name', 'Select Category')}}</strong>
{{Form::select('categories_name', $categories_name, null, ['class' => 'form-control'], array('name'=>'categories_name[]'))}}
</div>
#if (count($user_clubs)>0)
<table class="table table-striped">
<tr>
<th><strong>Club Name</strong></th>
<th></th>
<th></th>
</tr>
#foreach ($user_clubs as $club)
<tr>
<th>{{$club->club_name}} | {{$club->category->category_name}} </th>
<td>Edit</td>
<td>
{!!Form::open(['action' => ['ClubsController#destroy', $club->id], 'method' => 'POST', 'class' => 'float-right'])!!}
{{Form::hidden('_method','DELETE')}}
{{Form::submit('Delete', ['class' => 'btn btn-danger'])}}
{!!Form::close()!!}
</td>
</tr>
#endforeach
</table>
#else
<p>You Have No posts</p>
#endif
3.Category Model
class Category extends Model
{
public function user(){
return $this->belongsTo('App\User');
}
public function clubs(){
return $this->hasMany('App\Club');
}
}
4.Club Model
class Club extends Model
{
public function user(){
return $this->belongsTo('App\User');
}
public function category(){
return $this->belongsTo('App\Category');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js>">
onchange alert($("#categories_name").length);
console.log($("#categories_name").length);
$(document).ready(function(){
$("#categories_name").on("change", function(){
var category_id = $(this).val();
$("table tr").each(function(index){
if (index != 0) {
$row = $(this);
if ($row.attr('id')!=category_id) {
$row.hide();
}
else {
$row.show();
}
}
});
});
});
</script>
I wrote this script from answer below it still not working please, help me find where did I make mistake? where should I put the script?
//add category id to your tr's
#foreach ($user_clubs as $club)
<tr id="{{$club)->category->id}}">
//Rest of your code
</tr>
#endforeach
//Your jquery
$("#categories_name").on("change", function() {
var category_id = $(this).val();
$("table tr").each(function(index) {
if (index != 0) {
$row = $(this);
if ($row.attr('id')!=category_id) {
$row.hide();
}
else {
$row.show();
}
}
});
});
this is AdminUsersController method!!!!
<?php
namespace App\Http\Controllers;
use App\Http\Requests\UsersRequest;
use App\Photo;
use App\Role;
use App\User;
use Illuminate\Http\Request;
use App\Http\Requests;
class AdminUsersController extends Controller
{
public function index()
{
//
$users = User::all();
return view('admin.users.index', compact('users'));
}
public function create()
{
//
$roles = Role::lists('name','id')->all();
return view('admin.users.create', compact('roles'));
}
public function store(UsersRequest $request)
{
//
$input = $request->all();
if($file = $request->file('photo_id')) {
$name = time() . $file->getClientOriginalName();
$file->move('images', $name);
$photo = Photo::create(['file'=> $name]);
$input['photo_id'] = $photo->id;
}
$input['password'] = bcrypt($request->password);
User::create($input);
return redirect('/admin/users');
}
public function show($id)
{
//
return view('admin.users.show');
}
public function edit($id)
{
//
return view('admin.users.edit');
}
public function update(Request $request, $id)
{
//
}
public function destroy($id)
{
//
}
}
By this images are uploaded to /public/images
This is code im using to display in index.blade.php
<img src="/images/{{$user->photo ? $user->photo->file : 'no user photo'}}" alt="">
but images are not displayed in webpage i don't know why!!! please help me with this
my routes code:
<?php
Route::get('/', function () {
return view('welcome');
});
Route::auth();
Route::get('/home', 'HomeController#index');
Route::get('/admin', function(){
return view('admin.index');
});
Route::resource('admin/users', 'AdminUsersController');
this is my code in index.blade.php
<h1>users</h1>
<table class="table table-hover">
<thead>
<tr>
<th>Id</th>
<th>Photo</th>
<th>Name</th>
<th>Email</th>
<th>Role</th>
<th>Status</th>
<th>Created</th>
<th>Updated</th>
</tr>
</thead>
<tbody>
#if($users)
#foreach($users as $user)
<tr>
<td>{{$user->id}}</td>
<td><img scr="/images/{{$user->photo ? $user->photo->file : 'no user photo'}}"></td>
<td>{{$user->name}}</td>
<td>{{$user->email}}</td>
<td>{{$user->role->name}}</td>
<td>{{$user->is_active == 1 ? 'Active' : 'Not Active' }}"</td>
<td>{{$user->created_at->diffForHumans()}}</td>
<td>{{$user->updated_at->diffForHumans()}}</td>
</tr>
#endforeach
#endif
</tbody>
this is my output in which i cannot display photos but photo is uploaded into /public/images folder
okey first of all to show an image with laravel you need to use {{asset(..)}} in your <img/> ... example :
<img src="{{asset('...')}}" alt="">
then you will need to store your photos in public folder by using public_path() function for exemple
$imageName = $user->id.'.'.'jpg';
$request->file('img')->move(
public_path() . '/img/', $imageName
);
now to show the photo of your user in the public path or storage path you need to do this for exemple :
<img src="{{asset('/img/user->photo')}}" alt="">
I hope that will help you