Inserting data to related models - laravel

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)

Related

How To Make Reverse Relationships One To Many In 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>

Method Illuminate\Database\Eloquent\Collection::appends does not exist. I used kyslik/column-sortable package, sort and pagination are not working

Student Model
class Student extends Model
{
use Sortable;
protected $fillable = ['firstName', 'lastName', 'date', 'score', 'batch_id', 'subject_id', 'mark_id'];
public $sortable = [
'id', 'firstName', 'lastName', 'date', 'score', 'batch_id', 'subject_id', 'mark_id', 'created_at'
];
public function batch()
{
return $this->belongsTo('\App\Batch', 'batch_id');
}
public function subject()
{
return $this->belongsTo('\App\Subject', 'subject_id');
}
public function mark()
{
return $this->belongsTo('\App\Mark', 'mark_id');
}
public function role()
{
return $this->belongsTo('\App\Role', 'role_id');
}
}
Route
Route::get('/studentrecord', 'StudentController#sort');
Controller
public function sort()
{
$sort = Student::sortable()->paginate(5);
return view('/studentrecord', compact('sort'));
}
studentrecord.blade
<table class="table table-striped">
<thead>
<tr class="thead">
<th>#sortablelink('Exam Date')</th>
<th>#sortablelink('Student ID Number')</th>
<th>#sortablelink('Student Name')</th>
<th>#sortablelink('Batch')</th>
<th>#sortablelink('Subject')</th>
<th>#sortablelink('Results')</th>
<th>#sortablelink('Marks')</th>
<th>#sortablelink('Updated')</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#if($students->count())
#foreach($students as $student)
<tr class="tbody">
<td>{{$student->date}}</td>
<td>0001-00{{$student->id}}</td>
<td>{{$student->firstName.' '.$student->lastName}}</td>
<td>{{$student->batch->name}}</td>
<td>{{$student->subject->name}}</td>
<td>{{$student->score}}</td>
<td>{{$student->mark->name}}</td>
<td>{{$student->created_at->diffForHumans()}}</td>
<td>
<!-- View -->
#auth
#if(auth()->user()->role_id === 1)
<a href="/admin/editstudent/{{$student->id}}" class="btn btn-info form-control"><i
class="fa fa-edit" style="font-size:20px;color:#fff;"></i></a>
<form class="delete_form" action="/admin/removestudent/{{$student->id}}" method="POST">
#csrf
{{method_field("DELETE")}}
<button type="submit" class="btn btn-danger form-control">
<i class="fa fa-remove" style="font-size:20px;color:#fff;"></i>
</button>
</form>
#endif
#endauth
</td>
</tr>
#endforeach
#endif
</tbody>
</table>
<div>
{!! $students->appends(\Request::except('page'))->render() !!}
</div>
Laravel sort by descending or ascending with pagination.
if I clicked sort link it's not sorting but in url it changes to http://localhost:8000/studentrecord?sort=Batch&direction=asc and desc
please help me...thank you in advance
Instead of:
<th>#sortablelink('Student ID Number')</th>
Use this: <th>#sortablelink('id','Student ID Number')</th>
The first parameter of #sortablelink should be the column name in your database and the second parameter should be the name by which you want to display the column.
Do the same for all the table headings too.
Also, you need to add the following statement at the end of your table tag:-
</table>
{!! $students->appends(\Request::except('page'))->render() !!}
Here, div is not required.

How to redirect on reference after admin login

I have to redirect the admin to /admin/reference instead of /admin/index.
I have changed the LoginController,protected $redirectTo = '/admin/reference';.t The same with RegisterController, the same with the VerificationController and the RedirectIfAuthenticated but still no redirection.
LoginController:
protected $redirectTo = '/admin/reference';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
RegisterController:
protected $redirectTo = '/admin/reference';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
VerificationController:
protected $redirectTo = '/admin/reference';
AdminController:
public function index()
{
return view('admin.index');
}
Authenticate Middleware:
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
}
RedirectIfAuthenthicated:
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect('/admin/reference');
}
return $next($request);
}
index.blade.php:
This is what is currently shows
#extends('admin.layouts.app')
#section('content')
Willkommen!
#endsection
admin.reference.index:This is what i want it to show
#extends('admin.layouts.app')
#section('title', '| Übersicht Referenzen')
#section('content')
<div class="row justify-content-center">
<div class="col-12">
<div class="panel panel-default">
<div class="panel-heading"><h3>Referenzen</h3></div>
<div class="panel-heading">Seite {{ $references->currentPage() }} von {{ $references->lastPage() }}</div>
<table class="table table-bordered table-striped">
<tr>
<th>Name</th>
<th>Bilder</th>
<th>Priorität</th>
<th>Aktionen</th>
</tr>
#foreach ($references as $reference)
<tr>
<td width="65%">
<a href="{{ route('admin.reference.edit', $reference->id ) }}"><b>{{ $reference->title }}</b>
</a><br>
</td>
<td>
#if(!count($reference->images))<span style="color:#ff0000;font-weight:700;">0</span>#else{{ count($reference->images) }}#endif
</td>
<td>
{{ $reference->priority }}
</td>
<td>
<a href="{{ route('admin.reference.edit', $reference->id) }}" class="btn btn-info pull-left"
style="margin-right: 3px; display: inline-block;">Edit</a>
<div style="display: inline-block;">
{!! Form::open(['method' => 'DELETE', 'route' => ['admin.reference.destroy', $reference->id], 'data-item-id' => $reference->id ]) !!}
{!! Form::submit('Löschen', ['class' => 'btn btn-danger delete-submit','data-item-id' => $reference->id]) !!}
{!! Form::close() !!}
</div>
</td>
</tr>
#endforeach
</table>
</div>
<div class="text-center">
{!! $references->links() !!}
</div>
</div>
</div>
#endsection
I expect after the login to be redirected to /admin/reference instead of /admin/index.
I'm working on laravel 5.5 but I think this would help you. Try adding this to your login controller
protected function authenticated(Request $request, $user)
{
if ( $user->isAdmin() ) {// check role
return redirect('/admin/reference');;
}
return redirect('/anywhere');
}
protected function authenticated()
{
if ( Auth::user() ) {
return redirect('/admin/reference');
}
return redirect('/');
}
added a protected function into my LoginController and it worked.

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 (->).

Laravel - Many to Many - Model binding

I need some help.
I have these tables: users, buys and codecs. I have a many-to-many relationship: buys, codecs, buy_codec
Tables
Schema::create('codecs', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Schema::create('buys', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('name');
});
Schema::create('buy_codec', function (Blueprint $table) {
$table->increments('id');
$table->integer('buy_id')->unsigned();
$table->foreign('buy_id')->references('id')->on('buys')->onDelete('cascade');
$table->integer('codec_id')->unsigned();
$table->foreign('codec_id')->references('id')->on('codecs')->onDelete('cascade');
$table->timestamps();
});
This is my controller:
class UserBuyController extends Controller
{
public function create($userId)
{
$codecs = Codec::lists('name', 'id');
$usr = User::findOrFail($userId);
return view('buy.create', compact('usr', 'codecs'));
}
public function store($userId, Request $request)
{
$codecs = $request->input('codecs');
$usr = User::findOrFail($userId)->buy()->create($request->except('codecs'));
$usr->codec()->sync($codecs);
return redirect('user/'.$userId.'/buy');
}
public function edit($userId, $id)
{
$codecs = Codec::lists('name', 'id');
$buy = User::findOrFail($userId)->buy()->findOrFail($id);
return view('buy.edit', compact('buy', 'codecs'));
}
}
Create form
{!! Form::open(['method'=>'POST', 'action'=>['UserBuyController#store', $usr->id]]) !!}
<div class="form-group">
{!! Form::label('name', 'Name:') !!}
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-font"></i></span>
{!! Form::text('name', null, ['class'=>'form-control']) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('codecs', 'Outbound Codecs:') !!}
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-language"></i></span>
{!! Form::select('codecs[]', $codecs, null, ['class'=>'form-control', 'multiple'=>true]) !!}
</div>
</div>
{!! Form::submit('Submit', ['class'=>'btn btn-info']) !!}
{!! Form::close() !!}
And this is the edit form
{!! Form::model($buy,['url'=>url('user/'.$buy->user->id.'/buy/'.$buy->id),'method'=>'patch']) !!}
<div class="form-group">
{!! Form::label('name', 'Name:') !!}
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-font"></i></span>
{!! Form::text('name', null, ['class'=>'form-control']) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('codecs', 'Outbound Codecs:') !!}
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-language"></i></span>
{!! Form::select('codecs[]', $codecs, null, ['class'=>'form-control', 'multiple'=>true]) !!}
</div>
</div>
{!! Form::submit('Update', ['class'=>'btn btn-info']) !!}
{!! Form::close() !!}
Model binding doesn't work
Something is wrong but I don't know what.
This is my pivot table. I have 2 codecs associated with buy_id 3
And this is my edit page.
Nothing is selected.
Update
Model
class Buy extends Model
{
protected $guarded = ['id'];
public function codec() {
return $this->belongsToMany('App\Codec');
}
public function user() {
return $this->belongsTo('App\User');
}
}
class Codec extends Model
{
protected $guarded = ['id'];
public function buy() {
return $this->belongsToMany('App\Buy');
}
}
class User extends Authenticatable
{
public function buy() {
return $this->hasMany('App\Buy');
}
}
One solution would be to create an accessor for the codec ids and use that with Form::select() instead:
In your Buy model add the following accessor:
public function getCodecListAttribute()
{
return $this->codecs->pluck('id')->toArray();
}
Then change you select block to:
<div class="form-group">
{!! Form::label('codec_list', 'Outbound Codecs:') !!}
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-language"></i></span>
{!! Form::select('codec_list[]', $codecs, null, ['class'=>'form-control', 'multiple'=>true]) !!}
</div>
</div>
This will mean that when you try to get the value from the request you will have to use codec_list instead of codecs.
Hope this helps!
in the edit form: {!! Form::select('codecs[]', $codecs, null, ['class'=>'form-control', 'multiple'=>true]) !!} the default selected value is set as null. You should set here the list of ids of the associated codecs.
Hope this helps.

Resources