displaying multiple images from database in laravel - 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

Related

Field 'vaccine_id' doesn't have a default value

why i'm getting this error?
First view
` #foreach ($appointments as $appointment)
<div class="card m-2 p-2">
<div class="card-body">
<h6 class="card-title">Vaccine: {{ $appointment->vaccine }}</h6>
<div class="mb-6" style="float: right; margin-top: 10px">
<form action="/appointment/{{ $appointment->id }}">
<input type="submit" class="bg-black text-white rounded py-2 px-4 hover:bg-black"
value="Schedule Now">
</form>
</div>
</div>
</div>
#endforeach`
First view Controller
` public function showAppointment()
{
return view('appointmentForm');
}`
Second View
` <form action="/appointment/create" enctype="multipart/form-data" method="POST">
#csrf
<div class="name">
<label for="name" class="form-label">Name:</label>
<input type="text" name="name" id="name" placeholder="Enter name">
</div>
</form>`
Route
`Route::get('/appointment/{id}', [AppointmentController::class, 'showAppointment'])->middleware('guest');`
` public function showAppointment()
{
return view('appointmentForm');
}`
i have two migration file
` Schema::create('appointments', function (Blueprint $table) {
$table->id();
$table->string('vaccine');
$table->timestamps();
});`
` Schema::create('usersappointments', function (Blueprint $table) {
$table->id();
$table->foreignId('vaccine_id')->constrained('appointments')->onUpdate('cascade')->onDelete('cascade');
$table->string('name');
$table->timestamps();
});`
Model
` protected $fillable = [
'vaccine_id', 'name'
];`
Controller
` public function createAppointment(Request $request)
{
$data = $request->validate([
'name' => 'required'
]);
usersappointments::create($data);
return redirect('/');
}`
This is how it works; the user select vaccines he want then he will redirect to a page which he will input his name but i'm getting this error
You need to set input vaccine_id in second view in order to send data to controller
<form action="/appointment/create" enctype="multipart/form-data" method="POST">
#csrf
<div class="name">
<label for="name" class="form-label">Name:</label>
<input type="hidden" name="vaccine_id" value="" /> // here get the vaccine_id in value which is selected in first view
<input type="text" name="name" id="name" placeholder="Enter name">
</div>
</form>

Pre-Populating Parent Child Form from DB

I have tried prepopulating the forms from DB records, not happening for child form, I have use all conventions for Laravel table, pivot table etc., still nothing. The array display with the dd('$allTariffs') but doesn't show on view file, please help am stuck with
ErrorException
foreach() argument must be of type array|object, null given
Edit Component Code
<?php
namespace App\Http\Livewire\Admin;
use App\Models\Products;
use App\Models\Tariffs;
use Livewire\Component;
class AdminEditTariffsComponent extends Component
{
// public $productId;
public $tariffId;
public $allTariffs = [];
public $rowProducts = [];
public $tariffName;
public function mount ($tariffId)
{
$this->rowProducts = Products::all();
$tariff = Tariffs::where('id', $tariffId)->first();
$this->tariffName = $tariff->tariff_name;
// $allTariffs = $tariff->products()->where('tariffs_id', $tariffId)->get()->toArray();
$allTariffs = $tariff->products->find($tariffId);
// var_dump($allTariffs) ;
// dd( $allTariffs);
foreach ($allTariffs->products as $product)
{
['productId' => $product->pivot->products_id, 'basicCharge' => $product->pivot->basic_charge, 'additionalCharge' => $product->pivot->additional_charge];
}
}
public function updateStatus()
{
$tariff = Tariffs::find($this->tariffId);
$tariff->tariff_name = $this->tariffName;
$tariff->created_by = auth()->user()->id;
$tariff->save();
foreach ($this->allTariffs as $product) {
$tariff->products()->sync($product['productId'],
['basic_charge' => $product['basicCharge'],
'additional_charge' => $product['additionalCharge']]);
}
session()->flash('message', 'Tariff added successfully!');
return redirect('/admin/tariffs/');
}
public function addProduct()
{
$this->allTariffs[] = ['productId' => '', 'basicCharge' => '', 'additionalCharge' => ''];
}
public function removeProduct($index)
{
unset($this->allTariffs[$index]);
$this->allTariffs = array_values($this->allTariffs);
}
public function render()
{
$rowProducts = Products::all();
return view('livewire.admin.admin-edit-tariffs-component',['rowProducts'=>$rowProducts])->layout('layouts.admin.base');
}
}
Edit View
<div class="container-fluid">
<!-- Begin Page Content -->
<!-- Page Heading -->
<div class="row">
<div class="col-lg-8">
<div class="card shadow mb-4">
<div class="card-header py-3">
<h6 class="m-0 font-weight-bold text-primary">Edit Tariff</h6>
</div>
<div class="card-body">
<form wire:submit.prevent="editTariff">
#csrf
<div class="form-row">
<!-- Default input -->
<div class="form-group col-md-8">
<input type="text" class="form-control" placeholder="Enter Tariff Name"
wire:model="tariffName" required>
</div>
</div>
<hr>
<div class="card">
<div class="card-header">
<h6 class="text-primary">Products, Basic and Weight Charges</h6>
</div>
<div class="card-body">
<table class="table" id="products_table">
<thead>
<tr>
<th>Product</th>
<th>Basic Charge</th>
<th>Weight Charge</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach ($allTariffs as $index => $allTariff)
<tr wire:key="tariff-{{ $value->wireKey }}">
<td>
<select
wire:model="allTariffs.{{$index}}.productId"
class="custom-select custom-select-sm form-control form-control-sm">
<option value="">Select Product</option>
#foreach ($rowProducts as $product)
<option value="{{ $product->id }}">
{{ $product->product_name }}
</option>
#endforeach
</select>
</td>
<td>
<input type="text"
class="form-control custom-select-sm form-control form-control-sm"
placeholder="Basic Charge"
wire:model="allTariffs.{{$index}}.basicCharge" required>
</td>
<td>
<input type="text"
class="form-control custom-select-sm form-control form-control-sm"
placeholder="Weight Charge"
wire:model="allTariffs.{{$index}}.additionalCharge" required>
</td>
<td>
<a href="#" wire:click.prevent="removeProduct({{$index}})" class="btn btn-danger btn-circle btn-sm">
<i class="fas fa-trash"></i>
</a>
</td>
</tr>
#endforeach
</tbody>
</table>
<div class="row">
<div class="col-md-12">
<a href="#" wire:click.prevent="addProduct" class="btn btn-success btn-circle btn-sm">
<i class="fas fa-plus"></i>
</a>
</div>
</div>
</div>
</div>
<hr>
<div class="form-row">
<div class="form-group col-md-3">
<button type="submit" class="form-control btn btn-small btn-primary">Edit
Tariff</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- /.container-fluid -->
</div>
Model File
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Tariffs extends Model
{
use HasFactory;
protected $table = "tariffs";
public function products()
{
return $this->belongsToMany(Products::class, 'products_tariffs',
'products_id', 'tariffs_id')
->withPivot('basic_charge', 'additional_charge');
}
public function productstariffs()
{
return $this->hasMany(ProductsTariffs::class);
}
}
I have tried prepopulating the forms from DB records, not happening for child form, I have use all conventions for Laravel table, pivot table etc., still nothing. The array display with the dd('$allTariffs') but doesn't show on view file, please help am stuck with
ErrorException
foreach() argument must be of type array|object, null given .thankyou
In your foreach in your mount function, you are creating an array but you aren't assigning it to anywhere. Therefore, $allTariffs is empty.
Also, you're casting your variables by default as an array. You are setting $rowProducts as a Collection, however. But then in your render you are also getting the $rowProducts again. I'd suggest removing the = [] and removing the fetching of the $rowProducts each render.
public $allTariffs = [];
public $rowProducts;
public $tariffName;
public function mount ($tariffId)
{
$this->rowProducts = Products::all();
// This assumes the $tarrifId always exists. If this isn't the case, perhaps
// wrap the related code in an "if ($tariff instanceof Tariff)"
$tariff = Tariffs::find($tariffId);
$this->tariffName = $tariff->tariff_name;
foreach ($tariff->products as $product) {
$this->allTariffs[] = ['productId' => $product->id, 'basicCharge' => $product->pivot->basic_charge, 'additionalCharge' => $product->pivot->additional_charge];
}
}
public function render()
{
return view('livewire.admin.admin-edit-tariffs-component')->layout('layouts.admin.base');
}

I want to make validation for same user assigned using laravel

I am a beginner and I am trying to make validation for the user assigned when I assign the same user again when I submit so the error message should be shown, this user is already assigned please help me how to do this? thanks.
Controller
public function adduseraction(REQUEST $request) {
// Users_permissions::where('user_id',$request->userid)->get()-
// >pluck('user_Access_id');
$useradd=$request->get('userid');
$checkid=$request->get('multiusersid');
$array = array();
foreach($checkid as $id){
$array[] = array('user_id'=>$useradd,'user_Access_id'=>$id);
}
$user=Users_permissions::insert($array);
return redirect('admin')->with('success', 'Users has been assigned');
}
html view
<form action="{{route('adduseraction')}}" method="post">
{{ csrf_field() }}
<div class="col-sm-4">
<label>Select User</label>
<select name="userid" class="form-control" id="typeofworkday">
<option>Select User</option>
#foreach($users as $user)
<option value="{{$user->id}}">{{$user->name}}</option>
#endforeach
</select>
</div>
<br> <br> <br>
<div class="card-body">
<label>Select Muliple User or One</label>
<!-- Minimal style -->
<div class="row">
#foreach($users as $user)
<div class="col-sm-2">
<div class="form-check">
<input type="checkbox" id="check" name="multiusersid[]" value="
{{$user->id}}" class="form-check-input" >
<h5 style="position:relative;left:10px;">{{$user->name}}</h5>
</div>
<!-- checkbox -->
</div>
#endforeach
</div>
<!-- /.card-body -->
</div>
<br><br><br><br>
<div class="card-footer">
<button type="submit" name="btnsubmit" class="btn btn-primary col-
md-2 center">Submit</button>
</div>
</form>
Ok you can do something like below
First check does user already exists in the table and if exists return redirect with the error message or else insert the data
public function adduseraction(Request $request) {
$isUserAvailable = Users_permissions::where('user_id',$request->userid)->get()- >pluck('user_Access_id');
//If user already exists
if($isUserAvailable) {
return redirect('admin')->with('error', 'Users has been assigned');
}else{
$useradd=$request->get('userid');
$checkid=$request->get('multiusersid');
$array = array();
foreach($checkid as $id){
$array[] = array('user_id'=>$useradd,'user_Access_id'=>$id);
}
$user=Users_permissions::insert($array);
return redirect('admin')->with('success', 'Users has been assigned');
}
}

How to get the data after submit the form based on the form input value using laravel

My controller contain single function with multiple API calling when I returned the controller function to my view api data displayed automatically but i need to display the data while submit the form. Please suggest any solution.
My Controller Code
public function domaincheck(Request $request)
{
ini_set('max_execution_time', 300);
<!-- Domain Availability Check -->
$sld = $request['sld'];
$tld = $request['tld'];
$response = file_get_contents('https://resellertest.enom.com/interface.asp?command=check&sld='. $sld .'&tld='. $tld .'&uid=resellid&pw=resellpw&responsetype=xml');
$data = simplexml_load_string($response);
$configdata = json_encode($data);
$final_data = json_decode($configdata,true);
<!--Domain Name Suggestions -->
$response1 = file_get_contents('http://resellertest.enom.com/interface.asp?command=GETNAMESUGGESTIONS&uid=resellid&pw=resellpw&SearchTerm='. $sld .'&MaxResults=5&ResponseType=XML');
$data1 = simplexml_load_string($response1);
$configdata1 = json_encode($data1);
$final_data1 = json_decode($configdata1,true);
}
My view Code
<form class="form-horizontal" method="get">
<div class="form-group">
<div class=" col-lg-2"></div>
<div class="col-lg-8">
<div class="input-group m-b">
<span class="input-group-addon" style="padding-left:10px; background-color: #999;" class='unclickable'>www</span>
<input type="text" name="sld" class="form-control">
<span class="input-group-addon">
<select class="form-control" name="tld" style="width: 100px;">
<?php $j = 0; ?>
#foreach($final_data2['tldlist']['tld'] as $value)
<?php $j++; ?>
#endforeach
#for ($i = 0; $i < $j-1;)
<option value="{{($final_data2['tldlist']['tld'][$i]['tld'])}}">{{($final_data2['tldlist']['tld'][$i]['tld'])}}</option>
<?php $i++; ?>
#endfor
</select>
</span>
<span class="input-group-addon">
<button type="submit" class="btn btn-sm btn-success">Submit</button>
</span>
</div>
<p class="text-center text-dark customFont" >
#foreach($final_data as $key=>$value)
#if($key=='DomainName')
<b>{{$value}}</b> <b>-</b>
#endif
#if($key=='RRPText')
<b>{{$value}}</b>
#endif
#endforeach
</p>
{{print_r($final_data1)}}
When submit the form (Response) it shows the domain name is available or not available. Response1 is shows the domain name suggestions but it shows the data with out submit the form.Please suggest any solutions

POST data from input within loop

I have a lot of products from a database. I display them with a loop. When a user clicks "more", I want to display its details. The problem is, for example: I have four products A, B, C, and D. When a user clicks A's details, it displays D's details or randomly. How can I fix this? This is my code:
<form action="details" method="post" enctype="multipart/form-data">
#foreach($images as $image)
<div class="card" >
<div class="card-inside1" >
<div class="center">
<img class="card-img-top img-fluid" src="<?php echo asset('images').'/'.$image->image1 ?>" alt="Card image" >
</div>
<div class="card-body">
<input type="text" name="imagename" value="{{$image->product_name}}"></input>
<button type="submit" value="Submit" name="more" class="btn btn-primary ">More</button>
</div>
</div>
</div>
#endforeach
</form>
route
Route::post("details",'UserController#detail');
controller
public function detail(Request $req)
{
$productname = $req->input('imagename');
return $productname;
}
There is no need of using a form to accomplish what you want.
#foreach($images as $image)
<div class="card" >
<div class="card-inside1" >
<div class="center">
<img clas="card-img-top img-fluid" src="<?php echo asset('images').'/'.$image->image1 ?>" alt="Card image" >
</div>
<div class="card-body">
<input type="text" name="imagename" value="{{$image->product_name}}"></input>
More
</div>
</div>
</div>
#endforeach
Route:
Route::get("details/{imagename}",'UserController#detail');
Controller:
public function detail(Request $req)
{
$productname = $req->imagename;
return $productname;
}
UPDATE
The reason why is taking the last product is because you are sending all products through the form. and it takes the last one that sends, not the one you clicked.
view
#foreach($images as $image)
{{ $product->name }}
#endforeach
web.php
Route::get("details/{id}",'ProductController#show')->name('product.show');
ProductController.php
public function show($id)
{
$product = Product::find($id);
return $product
}

Resources