belongsToManyRelation not working in laravel 8 - laravel

I have many to many relation which is inserting data correctly but when I try to fetch data it gives me no data.
one table is boss and other is workers
Migration
<?php
public function up()
{
Schema::create('boss_worker', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('worker_id');
$table->unsignedBigInteger('boss_id');
$table->timestamps();
});
}
Boss model relation
public function workers()
{
return $this->belongsToMany(\App\Models\Admin\Worker::class,'boss_worker');
}
How I am trying to fetch data
public function index()
{
$boss = Boss::find(1);
dd($boss->workers);
}
How I am inserting data
$input = $request->all();
$workers = $input['workers'];
$input['workers'] = implode(',', $workers);
$boss = Boss::where('staff_id',$request->boss)->first();
$worker_gangs = $boss->workers()->sync($workers);
It is not fetching any data

use
public function index()
{
$boss = Boss::with('workers')->find(1);
}

When you call a relationship from a model you are calling to Illuminate\Database\Eloquent\Builder so, you can access and apply any filter or query with the Query Builder, to fetch the data from that relationship, you have to use these methods to execute the query
->get();
->first();
your code have to be:
$boss = Boss::find(1);
$workers = $boss->workers()->get();
dd($workers);
or you can make eager loading with the Boss model
$boss = Boss::with('workers')->find(1);
dd($boss->workers);

Related

Laravel ManyToMany Fail

i got this function in user model
public function kelas(){
return $this->belongsToMany('App/Kelas','user_classes','id_user','id_class')->withTimeStamps();
}
i got this function in kelas model
public function user(){
return $this->belongsToMany('App/User','user_classes','id_class','id_user');
}
My Controller
public function kelas()
{
$kelas = Kelas::all();
$namaguru = Auth::user()->name;
$idlogin = Auth::user()->id;
$kelasdiambil = User::get();
$kelaspengajar = Kelas::all()->where("namaguru",$namaguru);
return view('crudkelas', compact("kelas","kelaspengajar",'kelasdiambil'));
}
My pivot migration
Schema::create('user_classes', function (Blueprint $table) {
$table->unsignedBigInteger('id_user');
$table->unsignedBigInteger('id_class');
$table->timestamps();
$table->primary(['id_user','id_class']);
$table->foreign('id_user')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
$table->foreign('id_class')->references('id')->on('classes')->onDelete('cascade')->onUpdate('cascade');
});
I want to create a view that show all namekelas at classes table using this pivot table with condition where id_user == Auth::user()->id ....
#foreach($kelasdiambil->kelas as $pel)
<tr>
<td>{{$pel->namekelas}}</td>
<td>{{$pel->kode}}</td>
<td>Edit Hapus</td>
</tr>
#endforeach
Error
Property [kelas] does not exist on this collection instance. (View: I:\darinol\nictoschool\resources\views\crudkelas.blade.php)
in english language, i just wanna create a user and class table became manytomany relationship and make a view to show all classname at classes table using this pivot table where the condition is id_user at pivot == Auth::user()->id; :( help me
You have to write like this
public function kelas(){
return $this->belongsToMany('App\Kelas','user_classes','id_user','id_class')->withTimeStamps();
}
public function user(){
return $this->belongsToMany('App\User','user_classes','id_class','id_user');
}
You use collection of array
$kelasdiambil = User::get();
So You have to use like this
#foreach($kelasdiambil as $pel)
<td>{{$pel->kelas->namekelas}</td>
Or you have to use like this
$kelasdiambil = User::first();

Laravel : get the top 10 users from answer's survey table

I want to display the top 10 users who are answering for the surveys
I tried this
public function topuser()
{
$bestuser = Answer::whereRaw('id = (select max(count(`id`)) from Answer)')->get();
return view('dashboard.top')->with('bestuser', $bestuser);
}
But it gives me an error.
Answer model:
class Answer extends Model
{
protected $fillable = ['answer'];
protected $table = 'answer';
public function survey() {
return $this->belongsTo(Survey::class);
}
public function question() {
return $this->belongsTo(Question::class);
}
}
Answer Migrate file :
public function up()
{
Schema::create('Answer', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->integer('question_id');
$table->integer('survey_id');
$table->string('answer');
$table->timestamps();
});
}
How to fix that, please?
If you are looking for top users (those with the most posts), it would probably be easier to come from the User model angle. Thus, pull a count from the Answer relationship on the User model, something like this:
$bestuser = User::withCount('answers as answer_count')
->orderBy('answer_count', 'desc')
->take(10)
->get();
Or if you just want a simple list:
$bestuser = User::withCount('answers as answer_count')
->orderBy('answer_count', 'desc')
->take(10)
->pluck('answer_count', 'name');
you can do like this
public function topuser()
{
$bestuser = Answer::OrderBy('created_at', 'DESC')->take(10)->get();
return view('dashboard.top')->with('bestuser', $bestuser);
}

How to get weekly and monthly report in laravel?

I want to get weekly reports and monthly reports on my application, but I don't know where to start.
I use Laravel 5.7, I have tried a number of experiments that I have searched for on the internet, but they don't work.
My table
Schema::create('surat_keluars', function (Blueprint $table) {
$table->increments('id');
$table->string('nomor_surat')->unique();
$table->integer('instansi_id')->unsigned();
$table->string('perihal');
$table->date('tanggal_surat');
$table->date('tanggal_kirim');
$table->string('lampiran');
$table->timestamps();
$table->foreign('instansi_id')->references('id')->on('instansis');
});
My model
class SuratKeluar extends Model
{
protected $fillable = [
'nomor_surat', 'instansi_id', 'perihal', 'tanggal_surat', 'tanggal_kirim', 'lampiran'
];
public function instansi()
{
return $this->belongsTo('App\Instansi');
}
}
And and I have tried using this controller, but I don't know how to display it in view blade
public function day()
{
$data= SuratKeluar::select('id', 'nomor_surat', 'created_at')
->get()
->groupBy(function($val) {
return Carbon::parse($val->created_at)->format('m');
});
}
I hope someone can help me.
based on your question if you want to show it in view you can return the controller to the view like this:
public function day(){
$data= SuratKeluar::select('id', 'nomor_surat', 'created_at')
->get()
->groupBy(function($val) {
return Carbon::parse($val->created_at)->format('m')});;
return view('name_of_the_view')->with('name_of_variable_in_view', $data);
}
please make sure the $data variable is the data for your report by using var_dump like this
public function day(){
$data= SuratKeluar::select('id', 'nomor_surat', 'created_at')
->get()
->groupBy(function($val) {
return Carbon::parse($val->created_at)->format('m')});;
var_dump($data);
}
and please ensure that you already build the view for your review you can read the documentation in here https://laravel.com/docs/5.7/views

How do I add a new record ith belongsToMany and hasMany relationships using a pivot table?

I just setup model Asset with belongsToMany rooms and model Room with hasMany assets relationships. I also created a pivot table that stores both the ids of room and assets.
MODELS
class Asset extends Model
{
protected $fillable = [ 'name', 'slug', 'price' ];
public function room()
{
return $this->belongsToMany('App\Room');
}
}
class Room extends Model {
protected $fillable = [ 'number', 'status' ];
public function assets()
{
$this->hasMany('App\Asset'); }
}
}
MIGRATIONS
public function up()
{
Schema::create('assets', function (Blueprint $table)
{
$table->increments('id');
$table->string('name')->unique();
$table->string('slug');
$table->string('price');
$table->timestamps();
$table->softDeletes();
});
}
public function up()
{
Schema::create('asset_room', function(Blueprint $table) {
$table->integer('asset_id')->unsigned();
$table->foreign('asset_id')->references('id')->on('assets');
$table->integer('room_id')->unsigned();
$table->foreign('room_id')->references('id')->on('rooms');
$table->unique(['asset_id', 'room_id']);
$table->timestamps();
});
}
I added an asset via php artisan tinker as:
$asset = new App\Asset;
$asset->name = "Lamp";
$asset->slug = "lamp";
$asset->price = 40;
$asset->save();
Now how do I add an asset to a room so that it also adds an entry to the pivot table?
$room = new App\Room;
$room->number = 1;
$room->status = 1;
$room->asset...?
$room->save();
UPDATE
On Alexey's suggestion, I've updated the following function in Room modal since it's a belongsToMany and not a hasMany relationship.
public function assets()
{
$this->belongsToMany('App\Asset');
}
I created an asset with id 1. When trying to attach asset to room as:
$room->assets()->attach(1);
I get the following error:
PHP Fatal error: Call to a member function attach() on null in C:\xampp\htdocs\hotel\vendor\psy\psysh\src\Psy\ExecutionLoop‌​\Loop.php(90) : eval()'d code on line 1
which also breaks the Tinker mode (Psy Shell) execution.
First of all, since it's a many-to-many relationship, it should be belongsToMany():
public function assets()
{
return $this->belongsToMany('App\Asset');
}
To attach an asset to a room, use attach() method:
$asset = new App\Asset;
$asset->name = "Lamp";
$asset->slug = "lamp";
$asset->price = 40;
$asset->save();
$room = new App\Room;
$room->number = 1;
$room->status = 1;
$room->save();
$room->assets()->attach($asset->id);

Display values of a list table in eloquent using laravel 5

I have this table with 4 id's related to other tables.
Table List:
id table1_id table2_id table3_id table4_id
1 2 3 2 1
2 1 4 3 3
I want now to output the values related to that table's ids
id table1_name table2_name table3_name table4_name
1 jay student singer actor
2 jeane teacher drummer actress
ListController:
public function index()
{
$res = ListModel::with('table1','table2','table3','table4')->get();
$foreach($res as r){
return $r->table1_name;
}
return view('list.index',compact('res'));
}
My problem here is that the output will be null instead of jay.How can I display now the values?Please help..
list table
public function up()
{
Schema::create('list_table', function (Blueprint $table) {
$table->increments('id');
$table->string('table1_id');
$table->string('table2_id');
$table->string('table3_id');
$table->string('table4_id');
$table->timestamps();
});
}
//additional info
Table1 Model
public function list(){
return $this->belongsTo('App\ListModel');
}
List Model
public function table1(){
return $this->hasMany("App\Table1",'id','table1_id');
}
Updated Values
id crime_type_id crime_name_id crime_suspect_id crime_victim_id
1 1 1 1 1
Expected output:
crime_type_des crime_name_des crime_suspect_name victim_name
against property theft Mcdonald Hillary
ReportController:
public function index()
{
$display_crime = CrimeReport::all();
return view('crimereports.index',compact('display_crime'));
}
report_table:
public function up()
{
Schema::create('crime_reports', function (Blueprint $table) {
$table->increments('id');
$table->string('crime_type_id');
$table->string('crime_name_id');
$table->string('suspect_id');
$table->string('victim_id');
$table->timestamps();
});
}
//additional info
CrimeName Model
public function crimeReport(){
return $this->belongsTo('App\CrimeReport');
}
Crime Report Model
public function crimeName(){
return $this->hasMany("App\CrimeName",'id','crime_name_id');
}
//Rest for CrimeReportController
public function index()
{
$display_crime = CrimeReport::all();
return view('crimereports.index',compact('display_crime'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$display_crime_type = CrimeType::lists('crime_type','id');
$display_crime_name = CrimeName::lists('crime_description','id');
return view('crimereports.create',compact('display_crime_type','display_crime_name'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(CrimeNewReportRequest $request)
{
$input = $request->all();
CrimeReport::create($input);
return redirect()->back()->withSuccess("Fields were inserted!");;
}
Change your relation definition as below:
Table1 Model
public function list(){
return $this->hasMany('App\ListModel');
}
List Model
public function table1(){
return $this->belongsTo("App\Table1");
}
You need update your index method as below, you could dump $rows to check if this work.
ListController
public function index()
{
$res = ListModel::with(['table1','table2','table3','table4'])->get();
$rows = [];
$foreach($res as r) {
$rows[] = [r->table1->name, r->table2->name, r->table3->name, r->table4->name];
}
dd($rows);
}
Your accessing table1_name on the original model change the _ to -> ( $r->table1->name)
EDIT:
Now it's starting to become much more readable. Here are what I think the relationships should be.
CrimeReport.php
public function crimeType()
{
return $this->belongsTo(CrimeType::class);
}
public function crimeName()
{
return $this->belongsTo(CrimeName::class);
}
public function suspect()
{
return $this->belongsTo(Suspect::class);
}
public function victim()
{
return $this->belongsTo(Victim::class);
}
There really doesn't seem to be a need to define the inverse of any of there relationships right away, if the need arises later then add them but there is no point creating the relation just because its there.
Now to make showing the report easy lets use some joins instead or eager loading.
CrimeReportController.php
public function index()
{
$results = CrimeReport::query()
->join('crime_types as ct','ct.id', '=', 'crime_reports.crime_type_id')
->join('crime_names as cn','cn.id', '=', 'crime_reports.crime_name_id')
->join('suspects as s','s.id', '=', 'crime_reports.suspect_id')
->join('victims' as v','v.id', '=', 'crime_reports.victim_id')
->get([
'crime_report.*', //to get ids and timestamps
'ct.name as crime_type',
'cn.name as crime_name',
'suspect.name as suspent_name',
'victim.name as victim_name'
])
dd($results->toArray());
}
Now $results will still be a collection of CrimeReport so you can still have access to all the model goodies you might want to throw in there. In addition to that you also already have your table, you can just print these out into an html table and you have your report.
If you were wanted to add some cool search stuff to the query then you can use whereHas to do that:
//this would just go before the get()
$query->whereHas('suspect', function($q){
$q->where('hair_color','=','brown')
->whereBetween('height',5.8,6)
})
Of course you might also want to make some of those leftJoins instead since I assume they won't all have a victim/suspect

Resources