Laravel 8 make 2 relationship between the same model - orm

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.

Related

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

using v-for for rendering

i am build a laravel vue appliction and i want to render my categories from my categoriescontroller
heres my categorycontroller
public function index()
{
// geeting all the categories
$categories = Category::all();
return response([ 'categories' => CategoryResource::collection($categories), 'message' => 'Retrieved successfully'], 200);
}
heres my category.vue file
<tbody>
<tr v-for="category in categories.data" :key="category.id">
<td>{{ category.id }}</td>
<td>{{ category.name }}</td>
<td>11-7-2014</td>
<td><span class="tag tag-success">Approved</span></td>
</tr>
</tbody>
here also is my method in my category.vue file for loading my categorys
loadCategory(){
axios.get("api/category").then(({ data }) => (this.categories = data));
},
now i dont have any errorrs but its not rendering my categories either. please in need of assistance
since you're destructing the response inside the callback parameters .then(({ data }) you should directly render categories without .data field :
<tr v-for="category in categories" :key="category.id">
as you sending the data from laravel using api resource the actual data is loaded inside a data property. so you should extract it like this in the axios call
loadCategory(){
axios.get("api/category").then(({ data }) => (this.categories = data.categories.data));
},
yes i just quickly want to clearify , just incase someones sees this issue both answers from #Boussadjra Brahim and #sazzad was helpfull . so what i did was
first i took #Boussadjra Brahim suggestion and changed this
<tr v-for="category in categories" :key="category.id">
<td>{{ category.id }}</td>
<td>{{ category.name }}</td>
<td>11-7-2014</td>
<td><span class="tag tag-success">Approved</span></td>
</tr>
then i still got errors until i tried #sazzad suggestion but took out the .data attribute giving me this
loadCategory(){
axios.get("api/category").then(({ data }) => (this.categories = data.categories));
},
hope this helps someone also thanks again

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 reduce time to display a list (json object fetched from database) in a table using *ngFor structural directive?

I am fetching a json object using web API, and displaying it in a table using *ngFor Structural Directive. However the problem is, though the object gets fetched instantly and display in console, it takes time to display it in table. I want the object to be displayed in table instantly as soon as it comes into console.
component.html file;
<tr *ngFor="let data of orgData" id="{{data.Id}}">
<td hidden><input type="number" id="1" value="{{ data.Id }}"></td>
<td>{{ data.OrganisationName }}</td>
<td>{{ data.ContactPerson }}</td>
<td>{{ data.ContactPersonHPNo }}</td>
<td>{{ data.ContactPersonEmailId }}</td>
<td>{{ data.SubscriptionStatus }}</td></tr>
component.ts file;
ngOnInit() {
// making use of web API
this.httpService.get('http://url/StudyExAPI/GetOrganisations?Id=').subscribe(
data => {
this.orgData = data as string[];
// console.log(this.orgData);
},
(err: HttpErrorResponse) => {
console.log(err.message);
}
);}
If you have a lot of objects inside your array, you can use the virtual scroll viewport provided by package #angular/cdk which render only visible elements.

How to remove ??? characters on database query result with Laravel

I am have an issue that sounds new and don't know what is happening. I am retrieving data from database with Laravel eloquent.
In my controller:
public function index()
{
$suppliers = Supplier::all();
return response()->json($suppliers);
}
Its working just fine, the problem is the result object however is appearing as shown below with leading ???. All query results in the entire project is rendering just this way. I have tried to trim the project witn trim() but I realize this wont work on object.
����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������[{"id":1,"first_name":"Ronald","last_name":"Wekesa","mobile_number":"0717245218","work_phone":"07140000","phone_code":254,"fax":null,"email":"email#yaho.com","postal_address":"P.o
Box
323","town":"Kitale","zip":30200,"phisical_address":"Kiminini","company":"Wafutech","created_at":"2018-03-05
11:52:30","updated_at":"2018-03-05
11:52:30"},{"id":2,"first_name":"Ronald","last_name":"Wekesa","mobile_number":"0725645544","work_phone":"070025400","phone_code":2....
when I render the result in my vuejs front end as shown below I am getting blank loop, I mean the loop runs but with empty bullet list. I am suspecting this might have something with this fun behavior.
//My View component
<template>
<div>
<h3>Suppliers</h3>
<div class="row">
<div class="col-md-10"></div>
<div class="col-md-2">
<router-link :to="{ name: 'create-supplier'}" class="btn btn-primary">Add Supplier</router-link>
</div>
</div><br />
<table class="table table-hover table-striped table-responsive">
<thead>
<tr>
<td>First Name</td>
<td>Last Name</td>
<td>Company</td>
<td>Mobile Phone</td>
</tr>
</thead>
<tbody>
<tr v-for="supplier in suppliers">
<td>{{ supplier.first_name }}</td>
<td>{{ supplier.last_name }}</td>
<td>{{ supplier.company }}</td>
<td>{{ supplier.mobile_number }}</td>
<td><router-link :to="{name: 'edit-supplier', params: { id: supplier.id }}" class="btn btn-primary">Edit</router-link></td>
<td><button class="btn btn-danger" v-on:click="deleteSupplier(supplier.id)">Delete</button></td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
name:'displayAsset',
data(){
return{
suppliers: []
}
},
created: function()
{
this.fetchSuppliers();
},
methods: {
fetchSuppliers()
{
let uri = 'http://localhost/ims/public/api/suppliers';
this.axios.get(uri).then((response) => {
this.suppliers = response.data;
});
},
deleteSupplier(id)
{
let uri = `http://localhost/ims/public/api/suppliers/${id}`;
this.suppliers.splice(id, 1);
this.axios.delete(uri);
}
}
}
</script>
I have tried to re-install laravel but no difference. I have also re-installed my xampp server with the latest version but wan't lucky either. What is causing this and how can I resolve it. Thanks in advance.