How To Make Reverse Relationships One To Many In Laravel - laravel

I have two models that are User and Transactions and I have made a relationship OneToMany, my hasMany Relationship is working fine, but its reverse relationship is not working here is my Transaction Migration.
Schema::create('transactions', function (Blueprint $table) {
$table->id();
$table->string('transaction_id');
$table->foreignId('transaction_from')
->constrained('users')
->onUpdate('cascade')
->onDelete('cascade');
$table->foreignId('transaction_to')
->constrained('users')
->onUpdate('cascade')
->onDelete('cascade');
$table->integer('transaction_coins');
$table->string('transaction_note');
$table->boolean('transaction_status');
$table->timestamps();
});
and Here is my User Model, I created two Relationships.
public function transactions_from()
{
return $this->hasMany(Transaction::class, 'transaction_from');
}
public function transactions_to()
{
return $this->hasMany(Transaction::class, 'transaction_to');
}
This is working fine I got Transactions From and Transactions To but when I created Reverse Relationship Functions I am not getting required results.
public function user_from()
{
return $this->belongsTo(User::class, 'transaction_from', 'id');
}
public function user_to()
{
return $this->belongsTo(User::class, 'transaction_to', 'id');
}
and in my blade file I want to show the Name of the User who Made Transaction From and To show the User Name with Transaction To.
<td>
<div class="d-flex align-items-center">
<img src="{{ asset('assets\images\table\pic-1.jpg') }}" class="rounded-circle me-2 width36 height36" alt="">
<span>{{ $transaction->transaction_from->user_from->name }}</span>
</div>
</td>
Please suggest me where I am wrong.

you have made relation on your Transaction model with user_to and user_from on User model.
<td>
<div class="d-flex align-items-center">
<img src="{{ asset('assets\images\table\pic-1.jpg') }}" class="rounded-circle me-2 width36 height36" alt="">
<span>{{ $transaction->transaction_from->user_from->name }}</span>
</div>
</td>
and if here on your blade $transaction is your object of Transaction model you should do like this:
<td>
<div class="d-flex align-items-center">
<img src="{{ asset('assets\images\table\pic-1.jpg') }}" class="rounded-circle me-2 width36 height36" alt="">
<span>{{ $transaction->user_from->name }}</span>
</div>
</td>

Related

Opening one post instead of multiple posts

I've written a blog that's supposed to fetch data from the database. But when I click on the read more link, it keeps opening all the posts that are in the db instead of selecting only one specific post that I've clicked. Can some kindly assist me with this issue?
View
#foreach($data as $aboutus)
<div class="col-lg">
<img src="{{ asset('storage/'.$aboutus->image) }}" class="img-fluid shadow-lg" style="">
<p class="mt-3 text-success fw-bold fs-5 text-lg-start">{{$aboutus->title}}</p>
<p class="fs-6 text-lg-start"> {{$aboutus->description}}</p>
<p class="text-success fw-bold text-lg-start">{{$aboutus->button}}</p>
<!--<img src="images/hr-2.png" class="img-fluid float-start my-2">-->
</div>
#endforeach
Controller
public function show($id)
{
//
$data = AboutUs::find($id)->get();
return view('about.show')->with(compact('data'));
}
Route
Route::get('/about.show/{id:title}','App\Http\Controllers\WelcomeController#show')->name('about.show');

Unlimited Nested Categories not working, Method Illuminate\Database\Eloquent\Collection::childrenRecursive does not exist

I tried #foreach $categories->children() aswell in index, still gives the same error which is Method Illuminate\Database\Eloquent\Collection::childrenRecursive does not exist, whichever function i use i get the same error, I want to display all the categories and their subcategories. Do not seem to figure out how
Category:
public function parent()
{
return $this->belongsTo(Category::class, 'cat_id');
}
public function children()
{
return $this->hasMany(Category::class, 'cat_id');
}
public function childrenRecursive()
{
return $this->children()->with('childrenRecursive');
}
Controller:
public function index()
{
$categories = Category::with('childrenRecursive')->whereNull('cat_id')->get();
return view('categories.index',compact('categories'));
}
blade.php
#foreach ($categories->childrenRecursive() as $category)
<tbody>
<tr>
<td>
{{$category->name}}
</td>
<td data-cat-id="{{$category->id}}">
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary add-subcat-modal-trigger">
Add Subcategory
</button>
<!-- Modal -->
</td>
<td>
<form action="{{route('categories.destroy',$category->id)}}" method="POST">
#csrf
#method('DELETE')
<button class="btn btn-danger">Delete</button>
</form>
</td>
</tr>
#endforeach
The relationship definition seems to be logically incorrect.
Parent hasMany Children and Children belongsTo Parent seems logical
public function parent()
{
return $this->hasMany(Category::class, 'cat_id');
}
public function children()
{
return $this->belongsTo(Category::class, 'cat_id');
}
//Defining a relationship with eagerloading would not work
//and on top of it you are trying to eager load childrenRecursive within childrenRecursive relation definition
public function childrenRecursive()
{
return $this->children()->with('childrenRecursive');
}
#foreach ($categories as $cat)
#foreach($cat->children as $category)
<tbody>
<tr>
<td>{{$category->name}} </td>
<td data-cat-id="{{$category->id}}">
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary add-subcat-modal-trigger">
Add Subcategory
</button>
<!-- Modal -->
</td>
<td>
<form action="{{route('categories.destroy',$category->id)}}" method="POST">
#csrf
#method('DELETE')
<button class="btn btn-danger">Delete</button>
</form>
</td>
</tr>
</tbody>
#endforeach
#endforeach

Laravel foreign key reference

I'm trying to reference the description of a foreign key via a relation, like follows:
My model.
namespace App;
use Illuminate\Database\Eloquent\Model;
class Evento extends Model
{
//
protected $fillable = [
'idEvento',
'strNombreEvento',
'strDireccion',
'strCiudad',
'strCorreo',
'strTelefono',
'strEncargadoEvento',
'strNotas',
'idEscuela',
];
protected $primaryKey = 'idEvento';
public function escuela()
{
return $this->belongsTo('App\Escuela','idEscuela');
}
public function diaevento()
{
return $this->hasMany('App\diaEvento');
}
}
The relation
namespace App;
use Illuminate\Database\Eloquent\Model;
class Escuela extends Model
{
//
protected $fillable = [
'idEscuela',
'strNombreEscuela',
'bolPrincipal',
'strLogo',
'sitDiasUsuarioInactivo',
'sitDiasToleranciaCobro',
];
protected $primaryKey = 'idEscuela';
public function grupos()
{
return $this->hasMany('app\grupo');
}
public function eventos()
{
return $this->hasMany('app\eventos');
}
}
My view
#extends('layouts.app')
#section('content')
#guest
#else
<nav class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0">
<a class="navbar-brand col-sm-3 col-md-2 mr-0" href="#">Eventos</a>
</nav>
<div class="container-fluid">
<div class="row">
<nav class="col-sm-1 d-md-block bg-light sidebar">
<div class="sidebar-sticky">
<h6 class="sidebar-heading d-flex justify-content-between align-items-center px-3 mt-4 mb-1 text-muted">
<span>Acciones</span>
<a class="d-flex align-items-center text-muted" href="#">
<span data-feather="plus-circle"></span>
</a>
</h6>
<ul class="nav flex-column">
<li class="nav-item">
<span data-feather="home"></span>
<span class="sr-only"></span>
</li>
<li class="nav-item">
<a class="nav-link" href="/gymmgr/public/eventos/create">
<span data-feather="file"></span>
Nuevo
</a>
</ul>
</div>
</nav>
<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pb-2 mb-3 border-bottom">
<h1 class="h5">Catálogo</h1>
<div class="btn-toolbar mb-2 mb-md-0">
<div class="btn-group mr-2">
<button class="btn btn-sm btn-outline-secondary">Exportar</button>
</div>
</div>
</div>
<table class="table">
<thead class="thead-light">
<tr>
<th>Evento</th>
<th>Escuela</th>
<th>Dirección</th>
<th>Ciudad</th>
<th>Correo</th>
<th>Teléfono</th>
<th>Contacto</th>
</tr>
</thead>
<tbody>
#foreach($eventos as $evento)
<tr>
<td> {{ $evento->strNombreEvento }} </td>
<td>{{ $evento->escuela->strNombreEscuela }}</td>
<td>{{ $evento->strDireccion }} </td>
<td>{{ $evento->strCiudad }} </td>
<td>{{ $evento->strCorreo }} </td>
<td>{{ $evento->strTelefono }} </td>
<td>{{ $evento->strEncargadoEvento }} </td>
</tr>
#endforeach
</tbody>
</table>
</main>
</div>
</div>
#endguest
#endsection
My controller
public function index()
{
//
$eventos = evento::all();
return view('eventos.index', ['eventos'=>$eventos]);
}
The result.
The thing is that the same mechanics is working with another model, which I post:
namespace App;
use Illuminate\Database\Eloquent\Model;
class grupo extends Model
{
//
protected $fillable = [
'idGrupo',
'idEscuela',
'strNombreGrupo',
];
protected $primaryKey = 'idGrupo';
public function escuela()
{
return $this->belongsTo('App\Escuela','idEscuela');
}
public function horarioGrupo()
{
return $this->hasMany('App\horario_Periodicos');
}
}
The relation is the same as with evento above.
My view
#extends('layouts.app')
#section('content')
#guest
#else
<nav class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0">
<a class="navbar-brand col-sm-3 col-md-2 mr-0" href="#">Grupos</a>
</nav>
<div class="container-fluid">
<div class="row">
<nav class="col-sm-1 d-md-block bg-light sidebar">
<div class="sidebar-sticky">
<h6 class="sidebar-heading d-flex justify-content-between align-items-center px-3 mt-4 mb-1 text-muted">
<span>Acciones</span>
<a class="d-flex align-items-center text-muted" href="#">
<span data-feather="plus-circle"></span>
</a>
</h6>
<ul class="nav flex-column">
<li class="nav-item">
<span data-feather="home"></span>
<span class="sr-only"></span>
</li>
<li class="nav-item">
<a class="nav-link" href="/gymmgr/public/grupos/create">
<span data-feather="file"></span>
Nuevo
</a>
</ul>
</div>
</nav>
<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pb-2 mb-3 border-bottom">
<h1 class="h5">Catálogo</h1>
<div class="btn-toolbar mb-2 mb-md-0">
<div class="btn-group mr-2">
<button class="btn btn-sm btn-outline-secondary">Exportar</button>
</div>
</div>
</div>
<table class="table">
<thead class="thead-light">
<tr>
<th>Nombre del grupo</th>
<th>Escuela</th>
</tr>
</thead>
<tbody>
#foreach($grupos as $grupo)
<tr>
<td> {{ $grupo->strNombreGrupo }} ></td>
<td>{{ $grupo->escuela->strNombreEscuela }}</td>
</tr>
#endforeach
</tbody>
</table>
</main>
</div>
</div>
#endguest
#endsection
The controller
public function index()
{
//
$grupos = grupo::all();
return view('grupos.index', ['grupos'=>$grupos]);
}
I would appreciate your help.
Thanks.
I post my migrations, they where added today
The original Evento
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateEventosTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('eventos', function (Blueprint $table) {
$table->increments('idEvento');
$table->string('strNombreEvento', 200);
$table->string('strDireccion', 200);
$table->string('strCiudad', 200);
$table->string('strCorreo', 200);
$table->string('strTelefono', 20);
$table->string('strEncargadoEvento', 60);
$table->string('strNotas', 300);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('eventos');
}
}
These one was dump, thinking in a direct referent from the foreign table
From Evento to Escuela, no intermediate.
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class DeleteDiasEventoTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
//
Schema::dropIfExists('dias_eventos');
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
//
Schema::create('dias_eventos', function (Blueprint $table) {
$table->increments('idDiasEventos');
$table->integer('idEvento')->unsigned();
$table->foreign('idEvento')->references('idEvento')->on('eventos');
$table->integer('idDiaEventos')->unsigned();
$table->foreign('idDiaEventos')->references('id')->on('dia_eventos');
$table->unique(['idEvento','idDiaEventos']);
$table->timestamps();
});
}
}
Then I modified Evento, including the foreign key by itself.
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class ModifyEventoTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
//
Schema::table('eventos', function($table) {
$table->integer('idEscuela')->unsigned();
$table->foreign('idEscuela')->references('idEscuela')->on('escuelas');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('eventos', function (Blueprint $table) {
$table->dropForeign('eventos_idescuela_foreign');
$table->dropColumn('idEscuela');
});
}
}
Is your query returning array or object? If you dump it out, you might find that it's an array and all you need is an array access ([]) instead of an object access (->).

displaying multiple images from database in laravel

i am new to laravel and i want to ask how to display multiple images that is located in the database.
i have already inserted images in my database through this code
here is my try.blade.php.
<h3>Upload Image</h3>
<form name="form" action="imageupload" method="POST" enctype="multipart/form-
data">
<input type="hidden" name="_token" value="{{csrf_token()}}">
<input type="file" name="img[]" multiple="true">
<br><br>
<input type="submit" name="ok" value="Upload">
</form>
#if(Session::has('msg'))
{{ Session::get('msg')}}
#endif
and here is my web.php
Route::get('imageup','userLog#imageup');
Route::post('imageupload','userLog#imageupup');
and here is my controller
public function imageup(){
return view('try');
}
public function imageupup(Request $request){
if($request->hasFile('img')){
$image_array = $request->file('img');
$array_len = count($image_array);
for($i=0; $i<$array_len; $i++){
$image_size = $image_array[$i]->getClientSize();
$image_ext = $image_array[$i]->getClientOriginalExtension();
$new_image_name = rand(1234,9999).".".$image_ext;
$destination_path = public_path('/images');
$image_array[$i]->move($destination_path,$new_image_name);
$tab = new Tab1;
$tab->image_size = $image_size;
$tab->image_name = $new_image_name;
$tab->save();
}
return back()->with('msg','Images Uploade Successfully');
}
else{
return back()->with('msg','Please choose any image file');
}
}
this is the code in my table
Schema::create('tab1s', function (Blueprint $table) {
$table->increments('id');
$table->string('image_name');
$table->string('image_size');
$table->timestamps();
});
i hope someone can help me.
#foreach(json_decode($posts->images, true) as $images)
<div class="col-lg-2 col-md-2 col-sm-2">
<a href="{{ URL::to('img/offers/'.$images)}}"
class="portfolio-box">
<img src="{{ URL::to('img/offers/'.$images)}}"
class="img-responsive" alt="--">
<div class="portfolio-box-caption">
<div class="portfolio-box-caption-content">
<span class="glyphicon glyphicon-zoom-in"
style="font-size: 80px"></span>
</div>
</div>
</a>
</div>
#endforeach

Inserting data to related models

How to add a new data into related table ? I have two tables, the first is Edisi (Edition in English) table and Jurnal (Journal in English) table. The edisi table will contains many jurnal data, or in English the Edition table will contain many Journals data. My question is, how is the method create and save would look like ? I have created the function but it's not working.
Edisi table :
class CreateTableEdisi extends Migration
{
public function up()
{
Schema::create('edisi', function (Blueprint $table) {
$table->increments('id');
$table->string('judul')->unique();
$table->text('cover')->nullable();
$table->timestamps();
});
//Set FK di kolom id_edisi di table Jurnal
Schema::table('jurnal', function(Blueprint $table) {
$table->foreign('id_edisi')->references('id')->on('edisi')->onDelete('cascade')->onUpdate('cascade');
});
}
public function down()
{
Schema::table('jurnal', function(Blueprint $table) {
$table->dropForeign('jurnal_id_edisi_foreign');
});
Schema::drop('edisi');
}
}
Jurnal table :
class CreateTableJurnal extends Migration
{
public function up()
{
Schema::create('jurnal', function (Blueprint $table) {
$table->increments('id');
$table->string('judul', 200);
$table->string('penulis');
$table->text('abstrak');
$table->text('file');
$table->integer('id_edisi')->unsigned();
$table->timestamps();
});
}
public function down()
{
Schema::drop('jurnal');
}
}
Controller :
public function create()
{
return view('jurnal/create');
}
public function store(JurnalRequest $request)
{
$input = $request->all();
//Input PDF
if ($request->hasFile('file')) {
$input['file'] = $this->uploadPDF($request);
}
//Insert data jurnal
$jurnal = Jurnal::create($input);
return redirect('jurnal');
}
Show View :
#extends('template')
#section('main')
<div class="container sitecontainer single-wrapper bgw">
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12 m22">
<div class="widget searchwidget joblist">
<div class="large-widget m30">
<div class="post row clearfix">
<div class="col-md-4">
<div class="post-media">
<img alt="" src="{{ asset('fotoupload/' . $edisi->cover) }}" class="img-responsive">
<a class="btn btn-primary btn-block">{{ $edisi->judul }}</a>
</div>
</div>
<div class="col-md-8">
<div id="siswa">
<h2>Daftar Jurnal</h2>
#if (count($jurnal_list) > 0)
<table class="table">
<thead>
<tr>
<th>Judul</th>
<th>Penulis</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php foreach ($jurnal_list as $jurnal): ?>
<tr>
<td>{{ $jurnal->judul }}</td>
<td>{{ $jurnal->penulis }}</td>
<td>
<div class="box-button">
{{ link_to('jurnal/' . $jurnal->id, 'Detail', ['class' => 'btn btn-success btn-sm']) }}
</div>
<div class="box-button">
{{ link_to('jurnal/' . $jurnal->id . '/edit', 'Edit', ['class' => 'btn btn-warning btn-sm']) }}
</div>
<div class="box-button">
{!! Form::open(['method' => 'DELETE', 'action' => ['JurnalController#destroy', $jurnal->id]]) !!}
{!! Form::submit('Delete', ['class' => 'btn btn-danger btn-sm']) !!}
{!! Form::close() !!}
</div>
</td>
</tr>
<?php endforeach ?>
</tbody>
</table>
#else
<p>No Journals yet.</p>
#endif
<div class="tombol-nav">
Add new Journal to this edition
</div>
</div> <!-- / #jurnal -->
</div>
</div><!-- end post -->
</div><!-- end large-widget -->
</div><!-- end widget -->
</div><!-- end col -->
</div><!-- end row -->
</div><!-- end container -->
#stop
I'm new to Laravel and I'm stuck here. I tried everything I could (look at the controller) and when I try to add the journal data in the selected edition, it shows me error Constrains Fails. Thanks for your help!
First change $table->integer('id_edisi')->unsigned(); on your "jurnal" table to $table->integer('edisi_id')->unsigned();
Then add following method to "Jurnal" model
public function edisi()
{
return $this->belongsTo('App\Edisi');
}
if you don't like to change jurnal table as I showed earlier, modify above method as follows
public function edisi()
{
return $this->belongsTo('App\Edisi', 'id_edisi');
}
Then in controller
$jurnal_list = Jurnal::with('edisi')->get();
If you want to access "jurnal" from "edisi" add following method to the "Edisi" model
public function jurnals()
{
return $this->hasMany('App\Jurnal');
}
or for unmodified jurnals table.
public function jurnals()
{
return $this->hasMany('App\Jurnal', 'id_edisi');
}
Then in controller
$jurnal_list = Edisi::with('jurnals')->get();
Note: make sure to add $table variable to "Jurnal" and "Edisi" models, because normally table name needs be like s(ex:- Model: Post Table: posts, Model: Comment Table: comments)

Resources