Returning view: undefined variable Laravel - php

ERORR Undefined variable: listings
Users create a for sale advertising listing:
$listing->user_id = auth()->user()->id;
$listing->email= auth()->user()->email;
$listing->phone_number= auth()->user()->phone_number;
$listing->package = $request->session()->get('package');
$listing->save();
return view('user.dashboard');
After they get transferred to a dashboard page
#if($listings->isEmpty())
<div class="padding-top">
<h1 class="centre">None</h1>
</div>
#else
#endif
#foreach ($listings as $listing)
<div class="row">
<div class="container">
<div class="card">
<div class="card-body row">
<h5 class="card-title cardtitle col-lg-12 centre">{{$listing->address}}</h5>
incomplete html but just is an extract
EDIT ADDED FULL CONTROLLER Using return view('user.dashboard', ['listings' => $listing]); still throws an error
public function store(Request $request)
{
$this->validate($request, [
'image1' => 'image|nullable|max:1999',
'image2' => 'image|nullable|max:1999'
]);
// Handle File Upload
if($request->hasFile('image1')){
// Get filename with the extension
$filenameWithExt = $request->file('image1')->getClientOriginalName();
// Get just filename
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
// Get just ext
$extension = $request->file('image1')->getClientOriginalExtension();
// Filename to store
$fileNameToStore= $filename.'_'.time().'.'.$extension;
// Upload Image
$path = $request->file('image1')->storeAs('public/cover_images', $fileNameToStore);
} else {
$fileNameToStore = 'noimage.jpg';
}
$listing = new Listings;
$listing->user_id = auth()->user()->id;
$listing->email= auth()->user()->email;
$listing->phone_number= auth()->user()->phone_number;
$listing->package = $request->session()->get('package');
$listing->save();
$listing->image1 = $fileNameToStore;
return view('user.dashboard', ['listings' => $listing]);
}

Change
return view('user.dashboard');
into
return view('user.dashboard', compact('listing'));
I think the reason is pretty clear.

You need to pass $listing to your view like this:
return view('user.dashboard', compact('listing');
Edit:
Of course your variables must be named the same in your controller and view. You now have a mismatch as you name your variable $listing in your controller but call it as $listings in your view. Your code should be like this:
$listings->user_id = auth()->user()->id;
$listings->email= auth()->user()->email;
$listings->phone_number= auth()->user()->phone_number;
$listings->package = $request->session()->get('package');
$listings->save();
return view('user.dashboard', compact('listings');
Then you can call the variable as $listings in your view, so your view code doess not have to change.
EDIT 2:
$listing is ONE instance of the Listings model. So, you cannot call the empty() method on the object. I think you want to do something like this:
$listing = new Listings;
$listing->user_id = auth()->user()->id;
$listing->email= auth()->user()->email;
$listing->phone_number= auth()->user()->phone_number;
$listing->package = $request->session()->get('package');
$listing->save();
$listing->image1 = $fileNameToStore;
$listings = Listings::all();
return view('user.dashboard', compact('listings'));
Does this work out for you?
Ps. Do you want to set the image1 attribute AFTER you save it? This will get lost.

I think you are not importing model in the controller using namespace.
try to check using "Use auth" namespace
use App\Listing_Model;
use auth;
class DashboardController extends Controller {
public function index() {
$listing = new Listing_Model;
$listing->user_id = auth()->user()->id;
$listing->email= auth()->user()->email;
$listing->phone_number= auth()->user()->phone_number;
$listing->package = $request->session()->get('package');
$listing->save();
return view('user.dashboard');
}
}

Related

Profile Image not displaying

I am currently doing an instagram clone project, and I have encountered a problem where the profile image is appearing broken. I have tried to echo out the path, and the problem is, despite this being the path specified:
/storage/app/public/profile/9UHe7CSRK4V9SNESMz0BAYggmQOp2G04J3Ygcgtl.png
The browser is returning this path
/storage/app/public/profile//9UHe7CSRK4V9SNESMz0BAYggmQOp2G04J3Ygcgtl.png
So you can see that the browser is adding a second '/' after profile, I don't know why.
Here is my index.blade
<div class="col-3 p-5">
<img src="{{ dd($user->profile->profileImage()) }}" class="rounded-circle w-100">
</div>
My Profile model
class Profile extends Model
{
protected $guarded = [];
public function profileImage()
{
$imagePath = ($this->image) ? $this->image : 'profile/9UHe7CSRK4V9SNESMz0BAYggmQOp2G04J3Ygcgtl.png';
return '/storage/app/' . $imagePath;
}
Profiles controller
class ProfilesController extends Controller
{
public function index(User $user)
{
return view('profiles.index', compact('user'));
}
public function edit(User $user)
{
$this->authorize('update', $user->profile);
return view('profiles.edit', compact('user'));
}
public function update(User $user)
{
$this->authorize('update', $user->profile);
$data = request()->validate([
'title' =>'required',
'description' =>'required',
'url' =>'url',
'image' =>'',
]);
if(request()->hasfile('image')){
$imagePath = request()->file('image')->store('profile', 'public');
$image = Image::make(public_path("storage/{$imagePath}"))->fit(1200, 1200);
$image->save();
}
auth()->user()->profile->update(array_merge(
$data,
['image' => $imagePath]
));
return redirect("/Profile/{$user->id}");
}
}
Routes
Route::get('/p/create', [App\Http\Controllers\PostsController::class, 'create'])->name('posts.create');
Route::get('/p/{post}', [App\Http\Controllers\PostsController::class, 'show']);
Route::post('/p', [App\Http\Controllers\PostsController::class, 'store']);
Route::get('/Profile/{user}', [App\Http\Controllers\ProfilesController::class, 'index'])->name('Profile.show');
Route::get('/Profile/{user}/edit', [App\Http\Controllers\ProfilesController::class, 'edit'])->name('profiles.edit');
Route::patch('/Profile/{user}', [App\Http\Controllers\ProfilesController::class, 'update'])->name('profiles.update');
Thanks in advance
You could load it into base64 with this PHP code:
$type = pathinfo(dd($user->profile->profileImage()), PATHINFO_EXTENSION);
$data = file_get_contents(dd($user->profile->profileImage()));
$imgbase64 = "data:image/" . $type . ";base64," . base64_encode($data);
then use
<img src="<?php echo $imgbase64; ?>" class="rounded-circle w-100">
This will then display the base64 image, which doesn't store the URL in plain text.

new image in update form didn't change

I made an update form wherein in i can edit and update current uploads in my renting shop project.
but i've been having this problem wherein the image isn't changing both in the page and database, but when i checked the storage/public/images it stores the same current image whenever i try to try again.
but the rest in my form is working fine and already changeable except the image.
Here is in my CarsController.php
public function update(Request $request, $id)
{
$car = Car::find($id);
$car->car_brand = $request->car_brand;
$car->car_name = $request->car_name;
$car->description = $request->description;
$car->car_type_id = $request->car_type_id;
if ($request->hasFile('image_location')) {
Storage::disk('public')->delete($car->image_location); // remove the old file.
$path = $request->image_location->store('images', 'public'); // save the new image.
$car->image_location = $path;
}
$car->save();
$request->session()->flash('message', 'The item has been updated.');
return redirect('/selections');
}
Here's the form
<div class="form-group">
<label>Image</label>
<input type="file" class="form-control" name="image_location" required>
</div>
i don't know what could possibly wrong. anyone please enlighten me. Thanks in advance. Anyway the migrated column name is image_location
also here's in my store()
public function store(Request $request)
{
$car = new car;
$car->car_brand = $request->car_brand;
$car->car_name = $request->car_name;
$car->description = $request->description;
$car->car_type_id = $request->car_type_id;
$path = $request->image_location->store('images', 'public');
$car->image_location = $path;
$car->availability = $request->availability;
$car->save();
$request->session()->flash('message', 'The item has been added.');
return redirect('/selections');
}
I'm afraid your code works perfectly for me.
You could try adding some log lines and see where the problem lies:
use Illuminate\Support\Facades\Log;
if ($request->hasFile('image_location')) {
Log::debug('File has been found in request.');
// Check if the old car image exists.
Log::debug($car->image_location . (Storage::disk('public')
->exists($car->image_location)? ' exists': ' does not exist'));
Storage::disk('public')->delete($car->image_location); // Remove the old file.
// Check if the old car image (if it existed) has been deleted.
Log::debug($car->image_location . (Storage::disk('public')
->exists($car->image_location)? ' exists': 'does not exist'));
$path = $request->image_location->store('images', 'public'); // save the new image.
// Check if the new file has been saved correctly.
Log::debug($path . (Storage::disk('public')
->exists($path)? ' exists': 'does not exist'));
$car->image_location = $path;
}
After uploading a new image, my storage/logs/laravel.log shows:
[2019-12-28 10:18:03] local.DEBUG: File has been found in request.
[2019-12-28 10:18:03] local.DEBUG: images/WPMkdG56f4YXsd3IUJ3Ar1DbXF0QmtDz9bs0lKoI.gif exists
[2019-12-28 10:18:03] local.DEBUG: images/WPMkdG56f4YXsd3IUJ3Ar1DbXF0QmtDz9bs0lKoI.gif does not exist
[2019-12-28 10:18:03] local.DEBUG: images/s9RtTdFSv0Is8AgxDWX5c09zG8SyU987RVeC0di5.gif exists

Laravel- redirect with variable and display it in the view file

I have a controller
public function store(Request $request)
{if ($request->input('asc')){
$image = PropertyUser::where('user_id', '=', Auth::user()->id)->get();
foreach($image as $property)
{
$id = $property->property_id;
}
$image_ = Image::where('property_id', $id)->sortBy('description')->get();
return redirect('settings/photos');
How can i redirect with the $image_ variable and display it in my view file
#foreach ($image_ as $images)
<div class="image-warp"><img src="{{$images->filename}}"
style="width:100px;height:100px;"><br/><span style="color: #1b1e21">{{$images->description}}</span>
</div>
#endforeach
You can use the compact function to pass it to your view and reference it by the name.
return redirect('folder.name', compact('variableName');
return redirect()->route('folder.name', [$image]);
You can also send variable using below syntax also
return view('viewfile')->with('card',$card)->with('another',$another);
You can send data using redirect method. Those data will store inside Session Class.
return redirect('url')->with('message',$message);
like below
Session::get('variableName');
Session::get('message');
You should try this:
public function store(Request $request)
{if ($request->input('asc')){
$image = PropertyUser::where('user_id', '=', Auth::user()->id)->get();
foreach($image as $property)
{
$id = $property->property_id;
}
$image_ = Image::where('property_id', $id)->sortBy('description')->get();
return view('yourfolder.yourviewfile',compact('image_'));
Updated Answer
use Redirect;
public function store(Request $request)
{if ($request->input('asc')){
$image = PropertyUser::where('user_id', '=', Auth::user()->id)->get();
foreach($image as $property)
{
$id = $property->property_id;
}
$image_ = Image::where('property_id', $id)->sortBy('description')->get();
Redirect::to('settings/photos?image_='. $image_);
you can try with below code
return view('settings/photos')->with(['image' => $image_]);
Send an array of variables to your view:
return view('folder.viewfile', array(
'image_' => $image_,
'someother_variable' => $somevar,
));
Why you're using variable like this $image_ , you can use it simply like this $image or $whatEver
return view('folder.viewfile', compact('image'));
And now you can use this variable on view file as $image.
Do that in your controller function:
$request->session()->flash('order_id', $order_id);
And in view simply:
{{Session::get('order_id')}}
i just found myself in the same proble and solve with the help of you guys :)
on a complet example mi code ended like this:
mi FormCreate.php view recive an id from the previus page , so the url with out mask is "FormumariosCreate/16" in this example where the id is = 16 :
form:
<form method="post" action="{{ route('FormulariosStore2', $Formularios->idFormularios ) }}"> // is importan add the id on the rute
#csrf
<input type="text" name="textoPregunta" required="required" />
<button href="" class="btn btn-primary pull-right">Crear Nueva Pregunta</button>
</form>
rute in web.php:
Route::get('/FormulariosStore2/{idFormularios}', 'HomeController#FormulariosStore2')->name('FormulariosStore2');
Route::post('/FormulariosStore2/{idFormularios}', 'HomeController#FormulariosStore2')->name('FormulariosStore2');
and controler:
public function FormulariosStore2(Request $request,$id )
{
$validatedData = $request->validate([
'textoPregunta' => 'required|max:255',
]);
$ProyectoPreguntasF=ProyectoPreguntas::create($validatedData);
$Formularios = Formularios::findOrFail($id);
return redirect()->route('FormulariosCreate', $Formularios)->with('success','la operacion fue correcta.');
}
then it redirect to the rute "FormulariosCreate" with the id as a normal link with the id ,i hope it can add some content to the answer

How to update image using controller in laravel?

I want to update user image but it's not getting updated. I have used following controller for updating the image.. Can you suggest what's the mistake in controller function?
View part :
<div class="form-group">
<label>Image Upload</label>
<input type="file" name="image" id="image"><img src="{{ asset('public/images/' . $course->image) }}" width="200px"/></br>
</div>
Controller function :
public function update(Request $request, $id)
{
$data=Course::findOrFail($id);
if ($request->hasFile('image'))
{
$file = $request->file('image');
$timestamp = str_replace([' ', ':'], '-', Carbon::now()->toDateTimeString());
$name = $timestamp. '-' .$file->getClientOriginalName();
$data->image = $name;
$file->move(public_path().'/images/', $name);
}
$data->course_code = $request['course_code'];
$data->course_title = $request['course_title'];
$data->course_credit = $request['course_credit'];
$data->save();
return redirect('course');
}
Did you checked file permission on 'images' directory? It needs to have write permission for uploading files.
The problem is this,
$data->image = $name;
You set the value but you don't save it anywhere. You must add a saving line.
$data->save();
Note that, calling update() only saves what you pass in as parameters, doesn't save what you set through the mutators.
See The mistake/ solution of the problem is first i need to store the update value and then save the new image. So I made some changes in controller and solved it..
Here is controller code:
public function update(Request $request, $id)
{
$data=Course::findOrFail($id);
$data->update($request->all());
if ($request->hasFile('image'))
{
$file = $request->file('image');
$timestamp = str_replace([' ', ':'], '-', Carbon::now()->toDateTimeString());
$name = $timestamp. '-' .$file->getClientOriginalName();
$data->image = $name;
$file->move(public_path().'/images/', $name);
$data->save();
}
return redirect('course');
}

How to show comment's post with file on laravel?

My realtionship is like this: post Req.php have many comments CommentsRequest.php and comments have many file FileRequest.php. How to get file's detail from specified comments of post?
The model:
//Req.php
public function user()
{
return $this->belongsTo('App\User', 'profil_id', 'id');
}
public function commentsRequest()
{
return $this->hasMany('App\CommentRequest');
}
//CommentRequest.php
public function request()
{
return $this->belongsTo('App\Req');
}
public function user()
{
return $this->belongsTo('App\User', 'profil_id', 'id');
}
public function filesRequest()
{
return $this->hasMany('App\FileRequest', 'comreq_id');
}
//FileRequest.php
public function commentsRequest()
{
return $this->belongsTo('App\CommentRequest', 'comreq_id', 'id_comreq');
}
Store comment in CommentController.php
public function store($id)
{
$files = Input::file('filefield');
$user = Auth::user()->id;
$request = Req::find($id);
$isi = Input::get('comment');
$comment = CommentRequest::create(array('req_id' => $id, 'profil_id' => $user, 'comment' => $isi ));
foreach($files as $file) {
$names = "";
$x = new FileRequest();
if($validator->passes()){
$destinationPath = 'uploads/request';
$mime = $file->getClientOriginalExtension();
$upload_success = $file->move($destinationPath, $filename);
$names .= $filename;
$x->filename = rand(11111,99999).'.'.$mime;
$x->type = $mime;
$x->original_filename = $file->getClientOriginalName();
$comment->filesRequest()->save($x);
}
}
return view('request.show', compact('request'));
}
I want to show comment with file on view with this code but error
<ul>
#foreach($request->commentsRequest as $comment)
<h5>{{ $comment->komentar }} by {{ $comment->user->name }}</h5>
#foreach($comments->filesRequest->all() as $file)
<h5>{{ $file->filename }}</h5>
#endforeach
#endforeach
</ul>
How to solve this? I have stack with this problem. Sorry for bad english
You're getting this Undefined property error because you're trying to fetch $filesRequest property from $comments variable, which is a collection of comments. You need to fetch it from individual $comment:
#foreach($comment->filesRequest->all() as $file)
<h5>{{ $file->filename }}</h5>
#endforeach
You can also skip the call to all() because $comment->filesRequest returns the collection already, so the following should be enough:
#foreach($comment->filesRequest as $file)
<h5>{{ $file->filename }}</h5>
#endforeach

Categories