How to update image file in laravel? - laravel

I am trying to update an image of a database (One-To-Many and Belongs-To Relationships)
i have table proposition with fields id, proposition.
now the proposition table has relations with image table like this
image module
public function proposition()
{
return $this->belongsTo('App\Proposition');
}
proposition module
public function propositionimage() {
return $this->hasMany('App\PropositionImages');
}
now i want to update the image to an proposition:
i want to get the old value of input file and change it with the new value of input file .
the probleme is whene i use this
$proposition = Proposition::find($num_proposition);
$image = $proposition->propositionimage()->get();
it showing all the image of the proposition
i want to update all the image but one by one , any help plz ?
the HTML code
<img src="/images/{{ $propositonimage->imagename }}" alt="">
<div class="caption">
<input type="file" name="image" value="{{$propositonimage->imagename}}" >
</div>
the update function
public function update(PropositionRequest $request, $num_proposition)
{
$proposition = Proposition::find($num_proposition);
$image = $proposition->propositionimage()->get();
// echo "$image";
$images = Input::file('image');
if (Input::hasfile('image')) {
$rules2 = array('image' => 'mimes:jpeg,bmp,png');
$validator2 = Validator::make($images, $rules2);
if ($validator2->passes()) {
$distinationPath = 'images';
$imagename = $images->getClientOriginalName();
$upload_success = $images->move($distinationPath, $imagename);
$extension = $images->getClientOriginalExtension();
}
}

Im not 100% sure what the problem is. But it seems as you want to iterate the collection over the div?
proposition model
public function propositionimage()
{
return $this->hasMany(PropositionImages::class);
}
image model
public function proposition()
{
return $this->belongsTo(Proposition::class);
}
Then you return a view with proposition in a controller, and eager load PropositionImages?
public function index(){
$propositions = \Proposition::with('propositionimage')->get();
return view('image', compact('propositions'));
}
You will have a collection of proposition with corresponding images.
#forelse ($propositions as $propositon)
<img src="/images/{{ $propositon->imagename }}" alt="">
#if($propositon->propositionimage->count())
<div class="caption">
#foreach($propositon->propositionimage as $propositionimage)
name: {{$propositionimage->imagename}}<br>
<input type="file" name="image" value="{{$propositionimage->imagename}}" >
#endforeach
</div>
#else
No proposition image <br>
#endif
#empty
No images :(
#endforelse
Please add more details to your question otherwise.
Edit
I tried this at my local dev machine and it works.
All relations of propositionimage will be iterated to the corresponding proposition.

Related

Laravel Accessing Attributes & Slots Within Component Classes

I have a question about Laravel - Documentation - Accessing Attributes & Slots Within Component Classes
I read this section, and did some experiments. What I've found is that the closure only can return string but component.view, and what it returns would overwrite what is defined on the component view, which leads me to a question What use case is this feature for?
Could anyone make some examples of using this feature for me?
Anyone could help me with it will be so much appreciated.
If the string matches an existing view then it will render that view and not overwrite it. You can return an existing view as follows:
// app/View/Components/Post.php
public function render()
{
return function (array $data) {
// $data['componentName'];
// $data['attributes'];
// $data['slot'];
return 'components.post'; // /resources/views/components/post.blade.php
};
}
// views/components/post.blade.php
<div class="item">
<div class="title">
New Post
</div>
<div class="content">
<p>Content post...</p>
</div>
</div>
Example:
// component class
class Link extends Component
{
public $path = "";
public function __construct()
{
$this->path = request()->path();
}
public function render()
{
return function (array $data) {
if(isset($data['attributes']['href'])) {
$data['attributes']["link"] = $data['attributes']['href'];
if ($data['attributes']['href'] == "/".$this->path) {
$data['attributes']['active'] = $data['attributes']['class']." link-active-class";
} else {
$data['attributes']['active'] = $data['attributes']['class'];
}
}
return 'components.commons.link';
};
}
}
// component view
<a href="{{ $attributes['link'] }}" class="{{ $attributes['active'] }}">
{{ $slot }}
</a>
Usage:
<x-commons.link href="/module/news" class="primary-action">
<i class="fas fa-newspaper"></i> News
</x-commons.link>

Undefined variable: foods

hi guys am in need of assistance , i know this seems to be an easy one but am a bit confused , i have a foreach loop in my main.blade.php file, which shows foods from my database it works fine but when its clicked it meant to lead to the individual post and thats where i get the error
Undefined variable: foods
heres my foreach loop in main.blade.php file
#foreach($foods as $food)
<li class="item">
<a href="{{ route('Foods.show', $food->id) }}">
<img src="{{ Storage::disk('local')->url('food_images/'.$food->image ) }}" class="img-responsive w-25 p-3" alt="Food" >
<div class="menu-desc text-center">
<span>
<h3> {{ $food->title }}</h3>
{{ $food->body }}
</span>
</div>
</a>
<h2 class="white"> #{{ $food->price }}</h2>
</li>
#endforeach
heres my main.blade.php controller
public function LoadHome()
{
$foods = Food::all();
$foods = Food::orderBy('created_at','desc')->inRandomOrder()
->limit(12)
->get();
return view('pages.home')->withFood($foods);
}
and heres Foods.show controller function
public function show($id)
{
$foods = Food::Find($id);
return view('foods.show')->withFood($foods);
}
please what am i doing wrong
Have you tried passing data from your controller to the view using this something like this:
public function show($id)
{
$foods = Food::Find($id);
return view('foods.show')->with('foods', $foods);
}
or, if you're passing multiple variables to the view:
public function show($id)
{
$foods = Food::Find($id);
$something = "else";
return view('foods.show', compact('foods', 'something'));
}
Your view doesn't know what $foods is at that point, so it's always good practice to check that foods is set before the loop:
#if (isset($foods) && $foods->count() > 0)
#foreach($foods as $food)
...
#endforeach
#endif
See the official Laravel docs for more information.
If you want the variable to be named foods in the view then you would need to use withFoods not withFood:
return view(...)->withFoods($foods);
As mentioned in the other answers, there are other ways to pass data to the views as well.
There is no data being passed to a view.
This is how you pass data to a view:
public function LoadHome()
{
$foods = Food::orderBy('created_at','desc')->inRandomOrder()
->limit(12)
->get();
return view('pages.home', ['foods' => $foods])
}
If you always want to have $foods in main.blade.php you should place this in a service provider
View::share('foods', Food::orderBy('created_at','desc')->inRandomOrder()
->limit(12)
->get());
https://laravel.com/docs/7.x/views#sharing-data-with-all-views

how do i pass data value to another page via link in laravel?

i am trying to make a list of locations that you can rent. but to rent the place you need to fill in some information. to fill in this information you excess another page. how do i make it so laravel knows the page belongs to a certain location
this is what ive done now but i keep getting the error:
Call to undefined method App\Reservation::location()
as soon as i have filled in the fields of information
this is the blade file that links to the the create reservation file
#foreach
($locations as $location => $data)
<tr>
<th>{{$data->id}}</th>
<th>{{$data->name}}</th>
<th>{{$data->type}}</th>
<th><a class="btn" href="{{route('Reservation.index', $data->id)}}">rent</a></th>
</tr>
#endforeach
this is the create reservations blade
<form action="{{ route('location.store') }}" method="post">
#csrf
<label>title</label>
<input type="text" class="form-control" name="name"/>
<label>type</label>
<select>
<option value="0">klein</option>
<option value="1">groot</option>
</select>
<button type="submit" class="btn">inschrijven</button>
</form>
this is what the location controller looks like
public function store(Request $request)
{
$location = new Reservation;
$location->name = $request->get('name');
$location->type = $request->get('type');
$location->location()->associate($request->location());
$location->save();
return redirect('/location');
}
and the relationships in my models should also work
class Reservation extends Model
{
public function locations()
{
return $this->belongsTo('Location::class');
}
}
class Location extends Model
{
public function reservations()
{
return $this->hasMany('Registration::class');
}
}
ive been stuck at this all day and i really dont know where to look anymore
The error you are getting is because of the wrong function name, you are calling location, while it is locations.
public function locations(){}
&
$location->location()->associate($request->location());
and you can pass the variable as a query parameter, you'll need to pass this data as an array in your blade file.
Web.php
Route::get('/somewhere/{id?}, function(){
//do something
})->name('test');
Blade
route('test', ['id' => $id]);
Controller Method
public function store(Request $request, $id) //Adding the query parameter for id passed in Route.
{
$location = new Reservation;
$location->name = $request->get('name');
$location->type = $request->get('type');
$location->location()->associate($id);
$location->save();
return redirect('/location');
}

I want to upload and save image in database but when i try to do it Call to a member function images() on null error shown up

I am beginner in laravel and i want to make image uploading and saving app.
Everything is going cool but as i try to upload images it isnot saved to database.
But in public/gallery/images folder images are present.How this is possible without saving in database.
When i try to upload following error shown up:
FatalErrorException in GalleryController.php line 71:
Call to a member function images() on null
My controller is:
public function doImageUpload(Request $request){
//get the file from the post request
$file = $request->file('file');
//set my file name
$filename = uniqid() . $file->getClientOriginalName();
//move the file to correct location
$file->move('gallery/images',$filename);
//save image details into the database
$gallery = Gallery::find($request->input('gallery_id'));//get the gallery_id
$image = $gallery->images()->create([
'gallery_id'=>$request->input('gallery_id'),
'file_name'=>$filename,
'file_size'=>$file->getClientSize(),
'file_mime'=>$file->getClientMimeType(),
'file_path'=>'gallery/images/' . $filename,
'created_by'=>1,
]);
My view is:
<div class="row">
<div class="col-md-12">
<form action="{{url('image/do-upload')}}"
method="POST" enctype="multipart/form-data">
<label>Select image to upload:</label >
<input type="file" name="file" id="file">
<input type="submit" value="Upload" name="submit">
<input type="hidden" name="_token" value={{ csrf_token() }}>
</form>
</div>
and my image model is:
class Image extends Model
{
protected $fillable = [
'gallery_id','file_name','file_size','file_mime','file-path','created_by'
];
public function gallery(){
return $this->belongsTo('App\Gallery');
}
}
Being new to laravel i didnt get the actual error meaning Call to a member function images() on null??
How to fix this?
do a log debug on $gallery after you use the find method, there's a good chance it's not initialized, if the find method fails to find the id you've given it, it returns null
a good practice would be to verify you get an object back and verify your input contains gallery_id and that it is a number > 0
if ($request->has('gallery_id') && intval($request->input('gallery_id'))>0){
$gallery = Gallery::find($request->input('gallery_id'));//get the gallery_id
if ($gallery){
$image = $gallery->images()->create([
'gallery_id'=>$request->input('gallery_id'),
'file_name'=>$filename,
'file_size'=>$file->getClientSize(),
'file_mime'=>$file->getClientMimeType(),
'file_path'=>'gallery/images/' . $filename,
'created_by'=>1,
]);
} else {
return Response::make('no gallery found with this $request->input('gallery_id') gallery_id',404);
}
} else {
return Response::make('invalid gallery_id as input',400);
}
you could also create the image via the Image create method as is instead of using the gallery relationship, that would have created an image probably with the gallery_id of 0 if the galley_id input is incorrect.
$image = Image::create([
'gallery_id'=>$request->input('gallery_id'),
'file_name'=>$filename,
'file_size'=>$file->getClientSize(),
'file_mime'=>$file->getClientMimeType(),
'file_path'=>'gallery/images/' . $filename,
'created_by'=>1,
]);
I don't know if you resolved the problem, but I had the same issue and I found the solution.
When you send a form, you need to put a hidden input .
<input type"hidden" name="gallery_id" value="{{ $gallery->id }}">
I'm sure you work on the same project as me, DropZone Gallery, if so I think you have the solution

Laravel 4 search function validation

I've got an problem.
How could I validate an search function? Like if it fails to find the user, it'll display an error message. I've tried several things, but none of them works. Here's my form:
(search/search.blade.php)
<form id="custom-search-form" class="form-search form-horizontal pull-right" action="{{ URL::action('CharactersController#search') }}" method="get">
<div class="input-append span9">
<input type="text" class="search-query" name="character" placeholder="Character/guild name">
<button type="submit" class="btn"><i class="icon-search"></i></button>
</div>
I've tried to do something like: #if ($searchResult->count()) - it works, but it displays every time I enter the search site.
Here's my controller's acction:
public function search()
{
$name = Input::get('character');
$searchResult = Player::where('name', '=', $name)->get();
return View::make('search.search')
->with('name', $name)
->with('searchResult', $searchResult);
}
Shouldn't it be
#if(count($searchResult) > 0)
//Show results?
#endif
You could split your controllers methods into getSearch() to display the search form and then use postSearch() to display the results.
public function getSearch()
{
return View::make('search.search');
}
public function postSearch()
{
$name = Input::get('character');
$searchResult = Player::where('name', '=', $name)->get();
return View::make('search.search')
->with('name', $name)
->with('searchResult', $searchResult);
}
//search.blade example
#if(isset($searchResult))
#if($searchResult->count() > 0)
//display results
#else
//no results to display
#endif
#endif

Resources