I have done much research about this but I can't fetch the pivot table as I want.
I want to just fetch the measurement value from the pivot table-like structure you can see. Please check my all details first then you know what I want to show.
Model MeasurementPart.php
public function customers(){
return $this->belongsToMany(Customer::class, 'customer_measurements', 'measurementpart_id', 'customer_id')->withPivot('measurement');
}
Model Customer.php
public function measurementparts(){
return $this->belongsToMany(MeasurementPart::class, 'customer_measurements', 'customer_id', 'measurementpart_id')->withPivot('measurement');
}
Model CustomerMeasurement.php
public function customers(){
return $this->belongsToMany(Customer::class);
}
public function measurementparts(){
return $this->belongsToMany(MeasurementPart::class);
}
Here is my controller CustomerMeasurementController.php
public function editMeasurements(Request $request, $id){
$customer = Customer::with("measurementparts")->find($id);
$clothType = ClothType::all();
return view('customerMeasurements.edit', compact('customer', 'clothType'));
}
public function updateMeasurements(Request $request, Customer $customer){
$measurements = $request->input('measurement');
$filteredmeasurements = array_filter($measurements, function($a){
return $a !== null;
});
$measurement_id = $request->input('measurement_id');
$result = array_combine($measurement_id, $measurements);
$syncData = array();
foreach($result as $measurement_id=> $filteredmeasurements){
$syncData[$measurement_id] = array('measurement' => $filteredmeasurements);
}
$customer->measurementparts()->sync($syncData);
return redirect()->route('customers.index')->withStatus(__('Measurements successfully Updated.'));
}
View EditMeasurements.blade.php
<form action="{{ route('updateMeasurements', ['customer'=> $customer]) }}" method="POST">
#csrf
#foreach ($clothType as $item)
<tr>
<h3>{{ $item->name }}</h3>
<table>
#foreach ($item->measurementparts as $part)
<tr>
<td>
<img style="width: 191px;" class="img"
src="{{ asset('storage/image/' . $part->image) }}" alt="">
<input type="hidden" name="measurement_id[]" value="{{$part->id}}">
</td>
<td>{{ $part->name }}</td>
<td><input type="text" name="measurement[]" value="**I want to put here my measurment value**" class="form-control"></td>
</tr>
#endforeach
</table>
</tr>
<br>
<hr>
#endforeach
<input type="submit" value="Submit" class="btn btn-primary">
</form>
this is the image where I want to put
enter image description here
I'm pretty new to Laravel and need help. I'm creating an admin page where users can be assigned multiple roles by means of checkboxes. I have the usual many-to-many relationships set up and a pivot table, "roles_users" with two columns: role_id and user_id. Users' various roles display fine, but I'm having trouble with the update function. My form sends an array of roles to admincontroller#update, but of course they need to be associated with users -- and I can't figure out how to do that.
Here's my form:
<form method="POST" action="{{ route('admin.update') }}" enctype="multipart/form-data">
{{ csrf_field() }}
<table>
<thead>
<th>Name</th>
<th>Email</th>
#foreach ($roles as $role)
<th>{{ $role->name }}</th>
#endforeach
</thead>
<tbody>
#foreach ($users as $user)
<tr>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<input type="hidden" name="user[]" value="{{ $user->id }}">
#foreach($roles as $role)
<td><input type="checkbox" name="roles[]" value={{ $role->id }}
#if (in_array($role->id, $user->roles->pluck('id')->toArray() ))
checked ="1"
#endif />
</td>
#endforeach
</tr>
#endforeach
</tbody>
</table>
<input type="submit" class="tableSubmit" value="Update" />
Here's my update method:
public function update(Request $request, $id) {
$id = $request->input('user');
$user = User::with('roles')->find($id);
$user->roles()->sync(($request->roles), false);
return redirect('/admin');
}
This all throws an error, "Method Illuminate\Database\Eloquent\Collection::roles does not exist." But of course I do have a roles() method in my User model:
public function roles() {
return $this->belongsToMany('App\Role');
}
How do I pass through the user_id with the roles' ids, so that the sync method works? Thanks in advance for any help!
Here's my revised update method. It seems to work. I wonder if there's a more elegant solution, one that doesn't need a "foreach"?
public function update(Request $request) {
$users = (array_keys($request->roles)); // gets the user ids
foreach($users as $u) {
$user = User::find($u);
$user->roles()->sync(array_values($request->roles[$u]));
}
return redirect('/admin');
}
}
Your problem is that you are using the with method directly to the collection, the correct way is:
$user = User::where('id',$id)->with('roles')->first();
Hope it works!
EDIT:
Not sure why is a "false" after the array inside the sync method, try changing to this:
$user->roles()->sync($request->roles);
I cannot display session value in my view. I only want to display it to see if it's correctly set inside the controller. Is it correctly set in controller? How can I check?
I have this in view:
<div class="panel panel-success">
<form action="{{ route('get_table') }}" method="POST">
{{ csrf_field() }}
#foreach($tables as $data)
<button type="submit" name="tables" class="btn btn-primary" value="{{ $data->id }}">
{{$data->name }}
</button>
#endforeach
</form>
{{ Session::get('table_id') }}
</div>
This in ListController:
public function index() {
$tables = DB::table('tables')->get();
return view('welcome', compact('tables'));
}
public function getTable(Request $request) {
$table_id = $request->get('tables');
$request->session()->put('table_id', $table_id);
}
And this in web.php routes:
Route::get('/', 'ListController#index')->name('get_table');
Route::post('/', 'ListController#getTable');
I even tried
public function getTable(Request $request) {
$request->session()->put('table_id', '1234');
}
Nothing shows up in the view at {{ Session::get('table_id') }}
What am I doing wrong?
You can try this:
public function getTable(Request $request) {
$table_id = $request->get('tables');
return redirect()->back()->with('table_id',$table_id);
}
if you want to redirect to specific route then:
public function getTable(Request $request) {
$table_id = $request->get('tables');
return redirect()->route('RouteName')->with('table_id',$table_id);
}
and then in view:
#if(Session::has('table_id'))
{{ Session::get('table_id') }}
#endif
Hope you got your answer
I keep on getting this error whenever I try to enter the upload page.
Can anybody help?
I have already done the compact part to make sure that the variable is being passed to the view and also my route should be ok I think.
I tried using dd but all it does is keep on showing me the error
Error: Undefined variable: user (View: C:\xampp\htdocs\Evaluation\resources\views\upload.blade.php)
Here are my codes:
upload.blade.php
<form class="form-horizontal" method="post" action="{{ url('/userUpload')}}" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="hidden" name="user_id" value="{{$user->id}}">
<div class="form-group">
<label for="imageInput" class="control-label col-sm-3">Upload Image</label>
<div class="col-sm-9">
<input type="file" name="file">
</div>
</div>
<div class="form-group">
<div class="col-md-6-offset-2">
<input type="submit" class="btn btn-primary" value="Save">
</div>
</div>
</form>
UploadController:
public function upload(){
return view(‘upload’);
}
public function store(Request $request,$id){
$this->validate($request, [
'file' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
var_dump('has file '.$request->hasFile('file'));
if ($request->hasFile('file')) {
$image = $request->file('file');
$name = $image->getClientOriginalName();
$size = $image->getClientSize();
$id = $request->user_id;
$destinationPath = public_path('/images');
$image->move($destinationPath, $name);
$Image = new Image;
$Image->name = $name;
$Image->size = $size;
// $Image->user_id = $id;
//$Image->save();
$user->find($id);
dd($user);
$user->Images()->save($Image);
}
return redirect('/home');
}
public function test(){
$user = user_information::where('id')->get();
return view('upload', compact('user'));
}
Route: (this are my route)
Route::get('/UploadUser/upload','UploadController#upload’);
Route::post('/UploadUser','UploadController#store');
Route::post('/UploadUser/upload', 'UploadController#test');
Another question: I keep on getting this error when i try to upload a file, so what should I do?
Here is the error:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or
update a child row: a foreign key constraint fails (form.images,
CONSTRAINT images_user_id_foreign FOREIGN KEY (user_id) REFERENCES
usere_information (id)) (SQL: insert into images (name,
size, user_id, updated_at, created_at) values (download.png,
4247, 1, 2017-10-25 08:54:57, 2017-10-25 08:54:57))
Image model:
class Image extends Model
{
protected $fillable = array('name','size','user_id');
public function user_informations() {
return $this->belongsTo('App\user_information', 'user_id', 'id');
}
}
Images table:
Schema::create('images', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('size');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('user_informations');
$table->timestamps();
});
User_information table:
Schema::create('user_informations', function (Blueprint $table) {
$table->increments('id');
$table->engine = 'InnoDB';
$table->binary('signature');
$table->String('Name');
$table->timestamps();
});
User_information model:
class user_information extends Eloquent
{
protected $fillable = array('signature', 'Name');
protected $table = 'user_informations';
protected $primaryKey = 'id';
public function Images() {
return $this->hasOne('App\Image','user_id');
}
}
How to get the image?
Here is the view folder:
#foreach ($data as $object)
<b>Name: </b>{{ $object->Name }}<br><br>
Edit<br>
#foreach ($data3 as $currentUser)
<img src="{{ asset('public/images/' . $currentUser->Image->name ) }}">
#endforeach
#if($data3->count())
#foreach($data3 as $currentUser)
<a href="{!! route('user.upload.image', ['id'=>$currentUser->user_id]) !!}">
<button class="btn btn-primary"><i class ="fa fa-plus"></i>Upload Images</button>
</a>
#endforeach
#else
<a href="{!! route('user.upload.image', ['id'=>$object->id]) !!}">
<button class="btn btn-primary"><i class ="fa fa-plus"></i>Upload Images</button>
#endif
#endforeach
HomeController:
public function getInfo($id) {
$data = user_information::where('id',$id)->get();
$data3=Image::where('user_id',$id)->get();
return view('test',compact('data','data3'));
Because you didn't pass the user to your upload view, try to pass it like this :
public function upload(){
$id = 1 //The wanted user or if the user is authenticated use Auth::id()
$user = User::find($id);
return view('upload')->withUser($user);
}
Or if the user is authenticated use Auth in the view :
<form class="form-horizontal" method="post" action="{{ url('/userUpload')}}" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="hidden" name="user_id" value="{{auth()->id()}}">
<div class="form-group">
<label for="imageInput" class="control-label col-sm-3">Upload Image</label>
<div class="col-sm-9">
<input type="file" name="file">
</div>
</div>
<div class="form-group">
<div class="col-md-6-offset-2">
<input type="submit" class="btn btn-primary" value="Save">
</div>
</div>
</form>
For the second problem it's because in the route you have
Route::post('/UploadUser','UploadController#store');
and the your store method signature is
public function store(Request $request,$id){
The $id parameter that did the problem because it's not defined in the route so simply remove it from the method signatre
public function store(Request $request){
$this->validate($request, [
'file' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
if ($request->hasFile('file')) {
$image = $request->file('file');
$name = $image->getClientOriginalName();
$size = $image->getClientSize();
$id = $request->user_id; // here id is declared no need for the parameter
$destinationPath = public_path('/images');
$image->move($destinationPath, $name);
$Image = new Image;
$Image->name = $name;
$Image->size = $size;
$Image->user_id = $id;
$Image->save();
}
return redirect('/home');
}
For the third case you have to change the routes from :
Route::get('/UploadUser/upload','UploadController#upload’);
to
Route::get('/UploadUser/{user}/upload','UploadController#upload’)->name('user.upload.image');
And in the view add the id in the upload button url maybe like this :
{!! route('user.upload.image', ['user'=>$currentUser->id]) !!}
Then in the upload method :
public function upload(user_information $user){ // route model binding here
// dd($user); //for testing only :)
return view('upload')->withUser($user);
}
In the view change
<input type="hidden" name="user_id" value="{{auth()->id()}}">
To
<input type="hidden" name="user_id" value="{{$user->id()}}">
And you are good to go ;)
#foreach ($data as $currentUser)
<b>Name: </b>{{ $currentUser->Name }}<br><br>
Edit<br>
#if($currentUser->Image)
<img src="{{ asset('public/images/' . $currentUser->Image->name ) }}">
#endif
<a href="{!! route('user.upload.image', ['id'=>$currentUser->id]) !!}">
#endforeach
You have miss to pass id in your where condition,
public function test(){
$user = user_information::where('id',$id)->first();
return view('create1', compact('user'));
}
and you have to pass your user data into this,
public function upload(){
$user = user_information::where('id',$id)->first();
return view(‘upload’,compact('user'));
}
Hope it helps,
On your upload function, you have to pass the user variable because you use the $user in the view. So the controller will be
public function upload() {
$user = Auth::user();
return view('upload', compact('user'));
}
do not forget to change the $user based on your need.
You have to pass an $id variable into your test() method. Then please comment below what's the error next so I can follow you through.
Update
Since you don't want to pass an id. You can use:
public function test(){
$u = Auth::user();
$user = user_information::where('id', $u->id)->get();
return view('upload', compact('user'));
}
OR
Try to use first() instead of get().
More option:
I have noticed, you're using the upload() method here, why not passing the $user there? like so:
public function upload(){
$user = Auth::user();
return view(‘upload’, compact('user'));
}
1) I added the search bar to the view :
{!! Form::open(['method'=>'GET','url'=>'home','class'=>'navbar-form navbar-left','role'=>'search']) !!}
<div class="input-group custom-search-form">
<input type="text" class="form-control" name="search" placeholder="Search...">
<span class="input-group-btn">
<button class="btn btn-default-sm" type="submit">
<i class="fa fa-search">i
</button>
</span>
2) In my controller I'm displaying all my users in a table and the search bar is on top of it
public function index()
{
$user = User::all();
$search = \Request::get('search'); the param of URI
$users = User::where('name','=','%'.$search.'%')
->orderBy('name')
->paginate(20);
return view('home',compact('users'))->withuser($user);
}
Here is what the table looks like
#foreach($user as $users)
<th scope="row">1</th>
<td>show</td>
<td>{{$users->name}}</td>
<td>{{$users->city}}</td>
<td>{{$users->phone}}</td>
<td>{{$users->street}}</td>
<td>{{$users->national_id}}</td>
<td>{{$users->name}}</td>
</tr>
#endforeach
What I'm trying to get is when I search in the bar I want to do a loop like this
#foreach($users as $user)
{{ $user->name }}
#endforeach
and replace the view to the searched names only.
and here is the route for the index
Route::get('/home', 'HomeController#index');
how can I achive that ? sorry for the long question in advance.
You need to use like instead of =:
$users = User::where('name', 'like', '%'.$search.'%')
->orderBy('name')
->paginate(20);
Also, you're trying to create two queries. Much better way is to create local scope:
public function scopeSearch($q)
{
return empty(request()->search) ? $q : $q->where('name', 'like', '%'.request()->search.'%');
}
And then use it in controller:
public function index()
{
$users = User::search()->orderBy('name')->paginate(20);
return view('home', compact('users'));
}
This code will paginate all users if there is no search parameter or it will filter users and paginate them.