Laravel - Arranging images in ascending and descending order with links - php

I have a create method in my controller
public function create()
{
$image = PropertyUser::where('user_id', '=', Auth::user()->id)->get();
foreach($image as $property)
{
$id = $property->property_id;
}
$image_main = Image::where('property_id', $id)->get();
return view('settings.photos', ['image_array' => $image_main]);
}
This is my blade view
<form name="asc" action="{{route("settings.photos")}}" method="post" class="text-center">
#csrf
<input type="submit" value="Ascending " class="settings-photos-header2 text-center"/> |
</form><form name="dec" action="{{route("settings.photos")}}" method="post" class="text-center">
#csrf
<input type="submit" value= " Descending" class="settings-photos-header2 text-center"/>
</form>
<h2 class="settings-photos-header2 text-center">Photo Gallery</h2>
#foreach ($image_array as $images)
<div class="image-warp"><img src="{{$images->filename}}"
style="width:100px;height:100px;"><br/><span style="color: #1b1e21">{{$images->description}}</span>
</form>
</div>
#endforeach
Question-
How can i make the asc button sort the images in ascending order and des in descending order, is there a way to connect it to my controller, or is there a way to sort them in ascending and descending order through <a href> links?

First, foreach overrides $id in each iteration, so finally value of $id is $property_id value of last item from $image array.
You need to define relations.
In PropertyUser class add:
public function images() {
return $this->belongsTo(Image::class, 'property_id');
}
Then, in your create method in controller:
public function create(Request $request) {
// use direction query parameter to define asc or desc sorting
$order_direction = $request->query('direction');
$property_user = PropertyUser::where('user_id', '=', Auth::user()->id)
->with(['images' => function($query) use ($order_direction) {
$query->orderBy('id', $order_direction)
})->get();
// here you can access an array with associated images:
$images = $property_user->images;
return view('settings.photos', ['image_array' => $images]);
}
Your link to sorted images should like: Sort asc

Related

how do I do two way data binding on for each loop columns in laravel?

I have a foreach loop in a table that consist of multiple rows like this:
<td class="p-3 px-5">
<input type="text"
wire:model="email"
value="{{$row->email}}"
class="bg-transparent" >
</td>
Which gets data from:
$data = Teamuser::join('teams', 'teams.id', '=', 'team_user.team_id')
->join('users', 'users.id', '=', 'team_user.user_id')
->get([
'users.name as username',
'teams.name',
'users.email',
'team_user.role',
'team_user.id',
'team_user.user_id'
]);
return view('livewire.editusers',compact('data'));
I'm trying to use wire:model into a button to update data, the value doesnt works anymore. I need to do a two way data binding with something like this to insert data in my foreach's column.
public function edit($id)
{
$user = Teamuser::findOrFail($id);
$real = User::findOrFail($user_id);
$third = Team::findOrFail($team_id);
$this->username = $real->name;
$this->email = $real->email;
$this->team = $third->name;
$this->role = $user->role;
}
but since there are multiple $id in foreach table, how do I insert all the datas in the for each column?
#foreach($data as $row)
#php
App\Http\Livewire\Teamusers::edit($row->id,$row->user_id,$row-team_id);
#endphp
{{--call edit() function from teamusers component--}}
<td class="p-3 px-5">
<input type="text" wire:model="username" class="bg-transparent">
</td>
<td class="p-3 px-5">
<input type="text" wire:model="email" value="{{$row->email}}" class="bg-transparent" >
</td>
#endforeach
Edit:
I solved the binding problem by importing multiple models, but now it works like this.
I think its because the php code in the for each loop. But where else could i place it aside from there?
You're binding to your data incorrectly, you need to bind to a specific iteration within your $data.
I don't have your database or dataset, so I have replicated a simplified example below using the default User model.
Livewire Component
<?php
namespace App\Http\Livewire;
use App\Models\User;
use Livewire\Component;
class ModelIterator extends Component
{
public $users;
protected $rules = [
'users.*.email' => ['required']
];
public function mount()
{
$this->users = User::all();
}
public function render()
{
return view('livewire.model-iterator');
}
public function save($id)
{
$user = $this->users->where('id', $id)->firstOrFail();
$user->save();
}
}
Livewire Component View
<div>
#foreach ($users as $index => $user)
<div wire:key="user-field-{{ $user->id }}">
// Note the difference in how wire:model is defined here
<input type="text" wire:model="users.{{ $index }}.email" />
<button type="button" wire:click="save({{ $user->id }})">Save</button>
</div>
#endforeach
</div>

I need to fetch my pivot values from many to many relationship data

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

Laravel- arranging records in ascending and descending order

I have a create method in my controller
public function create()
{
$image = PropertyUser::where('user_id', '=', Auth::user()->id)->get();
foreach($image as $property)
{
$id = $property->property_id;
}
$image_main = Image::where('property_id', $id)->get();
return view('settings.photos', ['image_array' => $image_main]);
}
This is my photos.blade file
<form name="asc" action="{{route("settings.photos")}}" method="post" class="text-center">
#csrf
<input type="submit" value="Ascending " class="settings-photos-header2 text-center"/> |
</form><form name="dec" action="{{route("settings.photos")}}" method="post" class="text-center">
#csrf
<input type="submit" value= " Descending" class="settings-photos-header2 text-center"/>
</form>
<h2 class="settings-photos-header2 text-center">Photo Gallery</h2>
#foreach ($image_array as $images)
<div class="image-warp"><img src="{{$images->filename}}"
style="width:100px;height:100px;"><br/><span style="color: #1b1e21">{{$images->description}}</span>
</form>
</div>
#endforeach
Question- How can i make the asc button sort the images in ascending order and des in descending order, is there a way to connect it to my controller, or is there a way to sort them in ascending and descending order through any other means?
There are many ways you can achieve the sorting issue but as you have setup your page let me tell you the way you can sort records. Create another action which point to your settings.photos route
public function settings_photos($property_id) {
$form = Input::get('submit');
$orderBy = $form == "Ascending" ? "asc" : "desc";
# Fetch Images in of Specific Property
$list_of_images = Image::where('property_id', $property_id)
# Order by Asc/Desc
->sortBy('id', $orderBy)->get();
return view('settings.photos', ['image_array' => $list_of_images]); }
Now add Image->id to pass in your controller action by form
https://stackoverflow.com/questions/50432659/laravel-arranging-records-in-ascending-and-descending-order#
<form name="asc" action="{{route("settings.photos")}}" method="post" class="text-center">
#csrf
<input type="image_id" value="{{$id}}" />
<input type="submit" value="Ascending " class="settings-photos-header2 text-center"/> |
</form>
<form name="dec" action="{{route("settings.photos")}}" method="post" class="text-center">
#csrf
<input type="image_id" value="{{$id}}" />
<input type="submit" value="Descending" class="settings-photos-header2 text-center"/>
</form>
Now make some changes to your previous Controller code
public function create()
{
$image = PropertyUser::where('user_id', '=', Auth::user()->id)->get();
foreach($image as $property)
{
$id = $property->property_id;
}
$image_main = Image::where('property_id', $id)->get();
return view('settings.photos', ['image_array' => $image_main, 'id' => $id]);
}
As I told you there are various way to sort records even by Ajax but I suggest you using your code example. I also did not optimize the code.
Let me know if you have any question.
Thanks

Undefined variable:user laravel

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'));
}

One to one relationship while doing CRUD (create part)

I am having some trouble doing a one to one relationship with user_info table and userImage table. When I try to upload my image, it didn't save into my database and it user_id is 0. I managed to successfully do a one to many and one to one relationship in the past but not with CRUD together. Can anyone help me? Best to give me some example for me to refer or advice on what should I do. Thanks in advance
Here are my current codes:
createController:
public function create1(){
return view('create1');
}
public function store1(Request $request){
$this->validate($request, [
'input_img' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$user_info = Session::get('data');
$UserImage = new UserImage($request->input()) ;
if($request->hasFile('input_img')) {
$file = $request->file('input_img');
$fileName = $file->getClientOriginalName();
$destinationPath = public_path().'/images' ;
$file->move($destinationPath,$fileName);
$UserImage->userImage = $fileName ;
$UserImage = UserImage::create(['file' => $request->file('input_img')]);
$UserImage->user_infos()->associate($user_info);
}
$UserImage->save() ;
return redirect('/home');
}
HomeController(this is where I print out my information)
public function getInfo($id) {
$data = personal_info::where('id',$id)->get();
$data3=UserImage::where('user_id',$id)->get();
return view('test',compact('data','data3'));
blade.php (how I show the image in view)
#foreach ($data3 as $object9)
<img width="100" height="100" src="{!! $object9->userImage!!}">
#endforeach
UserImage model(in table I used binary format to store in DB)
class UserImage extends Eloquent
{
protected $fillable = array('userImage','user_id');
public function user_infos() {
return $this->belongsTo('App\user_info', 'user_id', 'id');
}
class user_info extends Eloquent
{
protected $fillable = array('Email', 'Name');
protected $table = user_infos';
protected $primaryKey = 'id';
public function UserImages() {
return $this->hasOne('App\UserImage','user_id');
}
}
create1.blade.php(this is how I upload the image)
<form class="form-horizontal" method="post" action="{{ url('/userUpload')}}" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group">
<label for="imageInput" class="control-label col-sm-3">Upload Image</label>
<div class="col-sm-9">
<input data-preview="#preview" name="input_img" type="file" id="imageInput">
<img class="col-sm-6" id="preview" src="" ></img>
</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>
You need to check out Laravel relations to clean up that code and simplify a lot of steps.
Change this line
$UserImage->user_infos()->associate($user_info);
For this
$UserImage->user_id = $user_info;
Take in mind that you're overriding the value of $UserImage inside that method.

Categories