got error when show data from other table laravel 5.2 - php

i have 2 tables.
users (name, username, email, password, remember_token)
dosen (iddosen, namedosen, address, phonenumber)
i want to show data from 2 tables in 1 view.
my User model :
public function profildosen()
{
return $this->belongsTo('App\Dosen');
}
Dosen model :
public function user()
{
return $this->hasOne('App\User');
}
view :
#foreach($dosen as $key => $value)
<strong>Kode Dosen :</strong> {{ $value->profildosen->iddosen }}<br>
<strong>Nama :</strong> {{ $value->profildosen->namedosen}}<br>
<strong>Alamat :</strong> {{ $value->profildosen->address}}<br>
<strong>No HP :</strong> {{ $value->phonenumber}} <br>
<strong>Email :</strong> {{ $value->email }}<br>
#endforeach
method :
$dosen = User::paginate(5);
return view('admin/dosen.index', compact('dosen'));
and got error :
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'dosen.id' in 'where clause' (SQL: select * from `dosen` where `dosen`.`id` is null limit 1) (View: D:\XAMPP\htdocs\infodosenku\resources\views\admin\dosen\index.blade.php)
what is the right method ?
UPDATE
Scheme Database
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('username');
$table->string('email')->unique();
$table->string('password', 60);
$table->boolean('admin')->default(0);
$table->rememberToken();
$table->timestamps();
});
Schema::create('dosen', function (Blueprint $table) {
$table->string('id');
$table->string('user_id');
$table->string('nipy');
$table->string('namadosen');
$table->string('alamatdosen');
$table->integer('notelpdosen');
$table->timestamps();
});
Route :
Route::resource('/admin/dosen', 'AdminController',
['except' => ['show']]);
Controller :
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Request;
use App\Http\Requests;
use App\Http\Requests\CreateDosenRequest;
use App\Dosen;
use App\User;
use Illuminate\Support\Facades\Input;
use DB;
class AdminController extends Controller
{
public function index()
{
// ambil semua data dosen
$dosen = User::paginate(5);
return view('admin/dosen.index', compact('dosen'));
}
public function create()
{
return view('admin/dosen.create');
}
public function store(CreateDosenRequest $request)
{
$user = User::create([
'name' => $request->input('name'),
'username' => $request->input('username'),
'email' => $request->input('email'),
'password' => bcrypt($request->input['password']),
'admin' => $request->input('admin')
]);
$dosen = Dosen::create([
'id' => $request->input('iddosen'),
'nipy' => $request->input('nipy'),
'namadosen' => $user->name,
'user_id' => $user->id,
'alamatdosen' => $request->input('alamatdosen'),
'notelpdosen' => $request->input('notelpdosen'),
]);
return redirect('admin/dosen')->with('message', 'Data berhasil ditambahkan!');
}
public function show($id)
{
$dosen = User::find($id);
return view('admin/dosen/show', compact('dosen'));
}
public function edit($id)
{
$dosen = User::find($id);
return view('admin.dosen.edit', compact('dosen'));
}
public function update($id)
{
$dosenUpdate = Request::all();
$dosen = User::find($id);
$dosen->update($dosenUpdate);
return redirect('admin.dosen')->with('message', 'Data berhasil diubah!');
}
public function destroy($id)
{
User::find($id)->delete();
return redirect('admin.dosen')->with('message', 'Data berhasil dihapus!');
}
}
And my View :
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-heading">Daftar Dosen</div>
<div class="panel-body">
<form class ="form-inline" action="{{ URL('/dosen/hasil/') }}" action="GET">
<div class="form-group">
<label for="cari">Cari Dosen </label>
<input type="text" class="form-control" id="cari" name="cari" placeholder="Masukan Nama Dosen">
</div>
<input class="btn btn-primary" type="submit" value="Cari">
</form><br>
<table class="table table-striped table-bordered">
<thead>
<tr>
<td>Nama</td>
<td>username</td>
<td>Actions</td>
</tr>
</thead>
<tbody>
#foreach($dosen as $key => $value)
<tr>
<td>{{ $value->name }}</td>
<td>{{ $value->username}}</td>
<td>
{!! Form::open(['url' => 'dosen/' . $value->id . '/edit', 'style'=>'display:inline-block']) !!}
{!! Form::hidden('_method', 'GET') !!}
{{ Form::button('<i class="fa fa-pencil-square-o"></i>', ['type' => 'submit', 'class' => 'btn btn-warning', 'title' => 'Ubah'] ) }}
{!! Form::close() !!}
<button title="Tampilkan" type="button" class="btn btn-success" data-toggle="modal" data-target="#myModal-{{ $value->id }}"><i class="fa fa-share"></i></button>
<!-- Modal -->
<div class="modal fade" id="myModal-{{ $value->id }}" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">{{ $value->namadosen }}</h4>
</div>
<div class="modal-body" style="overflow:auto;">
<strong>Kode Dosen :</strong> {{ $value->dosen->id }}<br>
<strong>NIP/NIPY :</strong> {{ $value->nipy }}<br>
<strong>Nama :</strong> {{ $value->namadosen }}<br>
<strong>Alamat :</strong> {{ $value->alamatdosen }}<br>
<strong>No HP :</strong> {{ $value->notelpdosen }} <br>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
{!! Form::open(['url' => 'dosen/' . $value->id, 'style'=>'display:inline-block']) !!}
{!! Form::hidden('_method', 'DELETE') !!}
{{ Form::button('<i class="fa fa-trash"></i>', ['type' => 'submit', 'class' => 'btn btn-danger', 'title' => 'Hapus'] ) }}
{!! Form::close() !!}
{!! Form::model($value, ['route' => ['admin.dosen.update', $value->id], 'method' => 'PUT']) !!}
</td>
</tr>
#endforeach
</tbody>
</table>
<h5><span class="label label-default">
Showing {!! $dosen->count() !!} results from total {!! $dosen->total() !!} results.
</span></h5>
<div> {!! $dosen->links() !!} </div>
</div>
</div>
</div>
</div>
</div>
#endsection
Dosen Model :
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Dosen extends Model
{
protected $table = 'dosen';
protected $fillable = ['iddosen', 'namadosen', 'user_id', 'nipy', 'kodeprogdidosen','alamatdosen', 'notelpdosen', 'tempatlahirdosen', 'tanggallahirdosen', 'agamadosen', 'emaildosen', 'sandidosen', 'jkldosen', 'fotodosen'];
protected $casts = [
'iddosen' => 'varchar',
];
public function dosen()
{
return $this->belongsTo('App\Dosen');
}
}
User Model :
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'username', 'email', 'password', 'admin',
];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function profildosen()
{
return $this->belongsTo('App\Dosen');
}
}

From Laravel Docs
Eloquent determines the default foreign key name by examining the name
of the relationship method and suffixing the method name with _id.
Your function name is profiledosen so Laravel will assume that in your in your Dosen Table you have id field as primary identifier.
You can change it from iddosen to id only and then change your method name to
public function dosen()
{
return $this->belongsTo('App\Dosen');
}
Alternatively you can supply the custom primary key to your method like
public function profildosen()
{
return $this->belongsTo('App\Dosen', 'iddosen');
}

The reason is that you badly identify your table id a so instead of dosen.id you should use dosen.iddosen
So the query should be like this: select * from dosen where iddosen is null limit 1
Or you may to use Laravel Query Builder More.
But the most important thing is that you need to know on what columns you will join your tables.
Hope it will help

Related

Laravel unknown column

I have a problem with this error:
https://pastebin.com/cgm5yq0P
This is my form:
https://pastebin.com/bSU5X5EC
This is my web.php (route controller):
Route::post('/komentarz', 'VideosController#postComment');
This is my VideoController postComment function:
https://pastebin.com/SYbEjB8H
This is my Comment model:
https://pastebin.com/SxHX6gTP
This is my User model comments function:
public function comments() {
return $this->hasMany('App\Comment');
}
This is my Video model comments function:
public function comments(){
return $this->belongsToMany('App\Comment')->withTimestamps();
}
And finally, Migration file named create_comments_table:
https://pastebin.com/2cHscQfq
My Routes:
https://pastebin.com/ki8FZ0C6
Please help me with this.. I dunno what is wrong
Your foreign keys are wrong. Change your migration to this.
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->unsignedInteger('video_id');
$table->foreign('video_id')->references('id')->on('videos')->onDelete('cascade');
Edit : This adds the comment and attaches it to the video and user.
// model fillable property
protected $fillable = [
'text', 'user_id', 'video_id',
];
// route
Route::post('/film/{id}/komentarz', 'VideosController#postComment');
// controller method
public function postComment(CreateCommentRequest $request, $id)
{
$video = Video::findOrFail($id);
$video->comments()->create([
'text' => $request->text,
'user_id' => auth()->id(),
]);
return 'works';
}
// form
{!! Form::open(['url' => "/film/{$video->id}/komentarz", 'method' => 'post','class' => 'form-horizontal']) !!}
<div class="form-group">
<div class="col-md-3 control-label">
{!! Form::label('text', 'Treść komentarza:') !!}
</div>
<div class="col-md-8">
{!! Form::textarea('text', null, ['class'=>'form-control', 'size' => '5x5']) !!}
</div>
</div>
<div class="form-group">
<div class="col-md-8 col-md-offset-3">
{!! Form::submit('Dodaj', ['class'=>'btn btn-primary btn-comment']) !!}
</div>
</div>
{!! Form::close() !!}
in comment model i see 'user' in fillable, not 'user_id'. i think it should be user_id. or you could use
protected guarded = [];
instead of using fillable array.

Call to a member function delete() on null / AdminHomeController.php line 26:

Using the multi_auth from laravel 5.3 im trying to make a delete/edit/update button.
Im trying to delete an user from the admin dashboard retrieving information from the users table.
Actually my first problem is with the destroy function.
This is my destroy route:
Route::get('{id}',[
'as' => 'admin.destroy',
'uses' => 'AdminHomeController#destroy'
]);
This is my controller from admin:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\User;
class AdminHomeController extends Controller
{
public function __construct()
{
$this->middleware('admin.user');
}
public function index()
{
$users = User::all();
return view("admin-home")->with('users', $users);
}
public function destroy($id)
{
$users = User::find($id);
$users->delete();
Flash::error('El usuario ' . $users->name . '$ ha sido eliminado con exito!');
return redirect()->route('admin-home');
}
}
View with delete button:
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="col-sm-offset-2 col-sm-8">
#if (count($users) > 0)
<div class="panel panel-default">
<div class="panel-heading">
Todos los Usuarios
</div>
<div class="panel-body">
<table class="table table-striped user-table">
<thead>
<th>Nombre:</th>
<th> </th>
<th>Email:</th>
<th> </th>
<th>Acciones:</th>
<th> </th>
</thead>
<tbody>
#foreach ($users as $user)
<tr>
<td> </td>
<td>{{ $user->name }}</td>
<td> </td>
<td>{{ $user->email }}</td>
<td> </td>
<td>
<i class="glyphicon glyphicon-trash" aria-hidden="true"></i>
</td >
<td>
<i class="fa fa-pencil-square-o" aria-hidden="true"></i>
</td>
<td> </td>
</tr>
#endforeach
</tbody>
</table>
</div>
#endif
</div>
</div>
</div>
</div>
#endsection
Thank you!
Check $id in
$users = User::find($id);
$users->delete();
Object $users is null because user didn't found in database or $id is incorrect
After playing around with the code i found this usefull:
In the view i had 2 buttons the delete and the edit ones, i changed:
{{ route('users.destroy', $user->id) }}
{{ route('users.edit', $user->id) }}
for:
{{ url('users.destroy', $user->id) }}
{{ url('users.edit', $user->id) }}
And now i can see the buttons without any problems, the issue now is the same as before, the function destroy gives me an error.
This is the route that causes the error:
Route::get('{id}',[
'as' => 'admin.destroy',
'uses' => 'AdminHomeController#destroy'
]);
Error: No query results for model [App\User].
This is my User model:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
And still can't find the issue.. #edwardstock

How to join in laravel infyom generator?

My controller is like this :
<?php
namespace App\Http\Controllers;
...
class UserController extends AppBaseController
{
/** #var UserRepository */
private $userRepository;
public function __construct(UserRepository $userRepo)
{
$this->userRepository = $userRepo;
}
public function index(Request $request)
{
$this->userRepository->pushCriteria(new RequestCriteria($request));
$users = $this->userRepository->all();
return view('users.index')
->with('users', $users);
}
}
..
My repository is like this :
<?php
namespace App\Repositories;
use App\Models\User;
use InfyOm\Generator\Common\BaseRepository;
class UserRepository extends BaseRepository
{
protected $fieldSearchable = [
'username',
'email',
'password',
'kdkotama',
'kdsatker',
'nama_lengkap',
'telp',
'level',
'kdtingkat'
];
public function model()
{
return User::class;
}
}
My model is like this :
<?php
namespace App\Models;
use Eloquent as Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Model
{
use SoftDeletes;
public $table = 'users';
protected $dates = ['deleted_at'];
public $fillable = [
'username',
'email',
'password',
'kdkotama',
'kdsatker',
'nama_lengkap',
'telp',
'level',
'kdtingkat'
];
protected $casts = [
'username' => 'string',
'email' => 'string',
'password' => 'string',
'kdkotama' => 'string',
'kdsatker' => 'string',
'nama_lengkap' => 'string',
'telp' => 'string',
'level' => 'string',
'kdtingkat' => 'string'
];
}
My view is like this :
#extends('layouts.app')
#section('content')
<section class="content-header">
<h1 class="pull-left">Users</h1>
<h1 class="pull-right">
<a class="btn btn-primary pull-right" style="margin-top: -10px;margin-bottom: 5px" href="{!! route('users.create') !!}">Add New</a>
</h1>
</section>
<div class="content">
<div class="clearfix"></div>
#include('flash::message')
<div class="clearfix"></div>
<div class="box box-primary">
<div class="box-body">
#include('users.table')
</div>
</div>
</div>
#endsection
<table class="table table-responsive" id="users-table">
<thead>
<th>No</th>
<th>Username</th>
<th>Email</th>
<th>Kotama</th>
<th>Satker</th>
<th>Nama Lengkap</th>
<th>Telp / No HP</th>
<th>Level</th>
<th>Tingkat</th>
<th colspan="3">Action</th>
</thead>
<tbody>
#foreach($users as $key => $user)
<tr>
<td>{!! ++$key !!}</td>
<td>{!! $user->username !!}</td>
<td>{!! $user->email !!}</td>
<td>{!! $user->kdkotama !!}</td>
<td>{!! $user->kdsatker !!}</td>
<td>{!! $user->nama_lengkap !!}</td>
<td>{!! $user->telp !!}</td>
<td>{!! $user->level !!}</td>
<td>{!! $user->kdtingkat !!}</td>
<td>
{!! Form::open(['route' => ['users.destroy', $user->id], 'method' => 'delete']) !!}
<div class='btn-group'>
</i>
{!! Form::button('<i class="glyphicon glyphicon-trash"></i>', ['type' => 'submit', 'class' => 'btn btn-danger btn-xs', 'onclick' => "return confirm('Are you sure?')"]) !!}
</div>
{!! Form::close() !!}
</td>
</tr>
#endforeach
</tbody>
</table>
My model was taken from the table users. I want to join with another table. kdkotama field and kdsatker field such : kotama code and satker code. I would like to join with table t_kotams and table t_satkers to get kotama name and satker name.
Using infyom laravel generator, I was so confused, how to implement. is there anyone who can help me?
Laravel infyom generator source :
http://labs.infyom.com/laravelgenerator/
https://github.com/InfyOmLabs/adminlte-generator/tree/5.3
Solution A: Edit generated code from infyom to implement relationship or just raw db query join tables in laravel:
Relationship. You can create something like
```
/**
* Get the user that owns the phone.
*/
public function user()
{
return $this->belongsTo('App\User', 'foreign_key', 'other_key');
}
There are many possibilities :
Defining Relationships
One To One
One To Many
One To Many (Inverse)
Many To Many Has Many
Through Polymorphic Relations
Many To Many Polymorphic Relations
Query builder - joins
something like this can be used
```
$users = DB::table('users')
->join('contacts', 'users.id', '=', 'contacts.user_id')
->join('orders', 'users.id', '=', 'orders.user_id')
->select('users.*', 'contacts.phone', 'orders.price')
->get();
Solution B: Use fields.json to generate your Model in infyom. Define relationships inside your *.json as documented here.
Note : infyom is a source generator, and everything is based on models, if your other tables don’t have models, adopt Solution A.

functions random from database in php?

I have a function:
function nomor_registrasi() {
$sql=mysql_query("select * from pendaftaran order by no_registrasi DESC LIMIT 0,1");
$data=mysql_fetch_array($sql);
$kodeawal=substr($data['no_registrasi'],6,7)+1;
if($kodeawal<10) {
$kode='SMKGJ00'.$kodeawal;
} else if ($kodeawal > 9 && $kodeawal <=99) {
$kode='SMKGJ0'.$kodeawal;
} else {
$kode='SMKGJ'.$kodeawal;
}
return $kode;
}
If a user registers from a form, the user will have no_registrasi, for example: last no_registrasi record in the table is SMKGJ006, so the user will have SMKGJ007, etc..
I'm starting learning the php framework: laravel.
How can I code this function using laravel?
I use laravel 4!
If you want to put your function to run when user register you need to put it in Controller that respond for registration of users.
The Controllers are in folder /app/controllers .
If you recent(1 minute ago) installed **laravel 4.1 and not have the Controller that respond for registration of users (like me, after installation I have a page on with is only image and you arrived and no link to register and login like after installation of yii), when you need to create it.
To create controller UsersController put in /app/controllers file with name UsersController.php and code:
<?php
class UsersController extends BaseController {
//!!show the form for registration from root /app/views/some_file name_like_register.blade.php in witch is html form
public function getRegister() {
return View::make('users/register');
}
//!! register user when post data come from form
public function postRegister() {
//Here you can put your function
$rules = User::$validation;
$validation = Validator::make(Input::all(), $rules);
if ($validation->fails()) {
return Redirect::to('public/users/register')->withErrors($validation)->withInput();
}
$user = new User();
$user->fill(Input::all());
$id = $user->register();
return $this->getMessage("Registered successfull.");
}
}
Add changes to User model. After
class User extends Eloquent implements UserInterface, RemindableInterface {
add
//form validation
public static $validation = array(
'email' => 'required|email|unique:users',
'username' => 'required|alpha_num|unique:users',
'password' => 'required|confirmed|min:6',
);
//for registration
protected $fillable = array('username', 'email', 'password');
//
public function register() {
//Here you can put your function
$this->password = Hash::make($this->password);
$this->activationCode = $this->generateCode();
$this->save();
Log::info("User [{$this->email}] registered. Activation code: {$this->activationCode}");
/*$this->sendActivationMail();*/ //send email with activation code, set 1 to isActive value
return $this->id;
}
protected function sendActivationMail() { /*do*/}
protected function generateCode() {
return Str::random();
}
Make file with name register.blade.php in /app/views/ with code:
#section('title')
#section('content')
<div class="container">
#if ($errors->all())
<div class="alert alert-danger">
#foreach ($errors->all() as $error)
<p>{{ $error }}</p>
#endforeach
</div>
#endif
<h1>Registration</h1>
{{ Form::open(array('url' => '/users/register', 'role' => 'form', 'class' => 'form-horizontal')) }}
<div class="form-group">
{{ Form::label('email', 'E-Mail', array('class' => 'col-sm-2 control-label')) }}
<div class="col-sm-5">
{{ Form::email('email', null, array('class' => 'form-control')) }}
</div>
</div>
<div class="form-group">
{{ Form::label('username', 'login', array('class' => 'col-sm-2 control-label')) }}
<div class="col-sm-5">
{{ Form::text('username', null, array('class' => 'form-control')) }}
</div>
</div>
<div class="form-group">
{{ Form::label('password', 'password', array('class' => 'col-sm-2 control-label')) }}
<div class="col-sm-5">
{{ Form::password('password', array('class' => 'form-control')) }}
</div>
</div>
<div class="form-group">
{{ Form::label('password_confirmation', 'retype pass', array('class' => 'col-sm-2 control-label')) }}
<div class="col-sm-5">
{{ Form::password('password_confirmation', array('class' => 'form-control')) }}
</div>
</div>
<div class="form-group">
<div class="col-sm-2"> </div>
<div class="col-sm-5">
<button type="submit" class="btn btn-primary">Go</button>
</div>
</div>
{{ Form::close() }}
In table user add your registraci cell. Table structure is
Schema::create('users', function(Blueprint $table) {
$table->increments('id');
$table->string('email')->unique();
$table->string('password', 60);
$table->string('username')->unique();
$table->boolean('isAdmin');
$table->boolean('isActive')->index();
$table->string('activationCode');
$table->rememberToken();
$table->timestamps();
// also add your registraci
$table->string('registraci', 200);
});
To turn on database driver open /app/config/database.php and change if need
//select mysql or other
'default' => 'mysql'
...
//database and other change here
'mysql' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'laravel',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
)
If I lost something you will get errors messages not like oops but real problems
To see errors go to /app/config/app.php and set to
'debug' => true,
Add a column with name no_registrasi in laravel table with users and use your old code when register new user, only change table name and other columns name.
https://laravel.com/docs/5.0/schema
Schema::table('users', function($table)
{
$table->string('no_registrasi');
});

Products list not seen while editing, using form model binding in laravel 5.1

In my ecommerce project, I have Product and Carousel Model.
Product.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Product extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $fillable = [
'code', 'name', 'description', 'special_note', 'sort', 'display', 'weight', 'enquiry'
];
public function carousels()
{
return $this->belongsToMany('App\Carousel')->withTimestamps();
}
}
Carousel.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Carousel extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $fillable = ['name', 'display', 'sort'];
public function products()
{
return $this->belongsToMany('App\Product')->withTimestamps();
}
public function getProductListAttribute()
{
return $this->products->lists('id');
}
}
Here's the controller:
public function create()
{
$products = Product::lists('name', 'id');
return view('admin.carousels.create', compact('products'));
}
public function store(Request $request)
{
$carousel = Carousel::create($request->all());
$carousel->products()->attach($request->input('product_list'));
return redirect()->back();
}
public function edit($id)
{
$carousel = Carousel::findOrFail($id);
$products = Product::lists('name', 'id');
return view('admin.carousels.edit', compact('carousel', 'products'));
}
public function update(Request $request)
{
dd($request->all());
}
The carousel form:
<div class="col-md-4 col-sm-4">
<div class="form-group">
{!! Form::label('name', 'Name:') !!}
{!! Form::text('name', null, ['class' => 'form-control input-sm', 'id' => 'name']) !!}
</div>
</div>
<div class="col-md-4 col-sm-4">
<div class="form-group">
{!! Form::label('sort', 'Sort:') !!}
{!! Form::text('sort', null, ['class' => 'form-control input-sm', 'id' => 'sort']) !!}
</div>
</div>
<div class="col-md-4 col-sm-4">
<div class="form-group">
{!! Form::label('display', 'Display:') !!}
{!! Form::select('display', ['Disabled' => 'Disabled', 'Enabled' => 'Enabled'], null, ['class' => 'form-control input-sm', 'id' => 'display']) !!}
</div>
</div>
<div class="col-md-12 col-sm-12">
<div class="form-group">
{!! Form::label('product_list', 'Products:') !!}
{!! Form::select('product_list[]', $products, null, ['class' => 'form-control input-sm', 'multiple']) !!}
</div>
</div>
<div class="col-md-12 col-sm-12">
<div class="form-group">
{!! Form::submit($submitButtonText, ['class' => 'btn btn-primary btn-block m_top_15', 'id' => $submitButtonId]) !!}
</div>
</div>
Now, the problem is that, when I use form model binding to edit the carousel form, I get no product displayed in the select box, though I can see all the products to select from. The selected products are not seen for the particular carousel.
What is the mistake that I have made ? Kindly help me out.
Thanks.
P.S: I am using Laravel 5.1 and came across this issue for the first time. Earlier I used to do this in Laravel 5 without any issue.
This may be related to how lists() is handled in 5.1. From the upgrade guide -
The lists Method
The lists method now returns a Collection instance instead of a plain
array for Eloquent queries. If you would like to convert the
Collection into a plain array, use the all method:
User::lists('id')->all(); Be aware that the Query Builder lists method
still returns an array.

Categories