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
Related
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.
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');
}
}
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');
}
I'm pretty new to Laravel and the MVC structure.
I want to add two buttons to a page, that will determine the order the products in it, appear. (price - low to high or high to low).
I'm trying to use the query string like so:
href="{{ url('store/' . $cat_url . '?order=ASC') }}">Price: Low to High</a> |
href="{{ url('store/' . $cat_url . '?order=DESC') }}">Price: Hign to Low</a>
This is my product view :
#foreach($products as $row)
<div class="col-md-6">
<h3>{{$row['title']}}</h3>
<p><img border="0" width="300" src="{{asset('images/' .$row['image'])}}"></p>
<p>{!! $row['article'] !!}</p>
<p><b>Price for pack:</b> {{ $row['price'] }}</p>
<p>
<input #if(Cart::get($row['id'])) disabled="disabled" #endif data-id="{{ $row['id']}}" type="button" value="Add to Order" class="add-to-order btn btn-success">
More Details
</p>
</div>
#endforeach
This is the model:
static public function getProducts($category_url, &$data)
{
$data['products'] = [];
if ($category = Category::where('url', $category_url)->first()) {
$category = $category->toArray();
$data['title'] = 'Candy | '. $category['title'];
$data['cat_url'] = $category['url'];
$data['cat_title'] = $category['title'];
$products = Category::find($category['id'])->products;
$data['products'] = $products->toArray();
}
}
And his is the controller : (I'm trying to get the the 'order' key using 'Input::')
public function products($category_url)
{
$order = Input::get('order');
Product::getProducts($category_url, self::$data);
return view('content.products', self::$data);
}
How can I add the query with the ORDER BY element to this model? How to get the value from the query string if the key appears?
Thanks a lot!
Try this:
static public function getProducts($category_url, &$data, $order = null){
$data['products'] = [];
if($category = Category::where('url', $category_url)->first()){
...
if ($order) {
$products = Category::find($category['id'])->products()->orderBy('price', $order)->get()
} else {
$products = Category::find($category['id'])->products;
}
...
}
}
You said you want to use MVC structure but your passed the order in url like query parameter with ? marks. This is not correct way in MVC you can use the Routing for that?
Give one try to this..
Register your Routes likes this
Route::get('store/{cat_url}/{order?}', "ControllerName#products");
Controller Method
use Illuminate\Http\Request;
public function products(Request request, $cat_url, $order="asc")
{
Product::getProducts($cat_url,$order, self::$data);
return view('content.products', self::$data);
}
Model Method
static public function getProducts($category_url, $order,&$data)
{
$data['products'] = [];
if ($category = Category::where('url', $category_url)->orderBy("your_field_name",$order)->first()) {
$category = $category->toArray();
$data['title'] = 'Candy | '. $category['title'];
$data['cat_url'] = $category['url'];
$data['cat_title'] = $category['title'];
$products = Category::find($category['id'])->products;
$data['products'] = $products->toArray();
}
}
Your links
href="{{ url('store/' . $cat_url . '/asc') }}">Price: Low to High</a> |
href="{{ url('store/' . $cat_url . '/desc') }}">Price: Hign to Low</a>
Happy Coding...
I'm including a file in laravel and its throwing me the following error:
Method Illuminate\View\View::__toString() must not throw an exception
I've included the file as so:
#include('users.opentasks')
I'm using two includes on the same page, but if I use one it doesn't make a difference.
I'm not really sure what this means and how to fix this bit of a newbie here. Hope someone can help.
My code is as follows:
UserController.php
public function profile() {
$status = "closed";
$data["projects"] = $projects = Auth::user()->projects()->where('status', '!=', $status)
->paginate(4);
//$data["tasks"] = $tasks = Auth::user()->tasks->paginate(4);
// $data["tasks_pages"] = $tasks->links();
//Comments pagination
$data["projects_pages"] = $projects->links();
if(Request::ajax())
{
$html = View::make('users.openprojects', $data)->render();
return Response::json(array('html' => $html));
// $html = View::make('users.opentasks', $data)->render();
// return Response::json(array('html' => $html));
}
echo View::make('users.profile')->with('projects', $projects);
}
public function opentasks() {
$user = User::with(array('tasks', 'tasks.status'))->find(Auth::user()->id);
return View::make('users.opentasks')->with('user', $user);
}
profile.blade.php
#extends("layout")
#section("content")
#include('users.openprojects')
#include('users.opentasks')
#stop
opentasks.blade.php
#foreach($user->tasks as $task)
{{ $task->task_name }}
{{ $task->task_brief}}
#if(!is_null($task->status))
{{ $task->status->status_name }}<br/><br/><br/><br/>
#endif
#endforeach
You might want to do it like this:
if(Request::ajax())
{
// --- this part of the code is odd
$html = View::make('users.openprojects', $data)->render();
return Response::json(array('html' => $html));
// ---
} else {
$user = User::with(array('tasks', 'tasks.status'))->find(Auth::user()->id);
$data = array(
'user' => $user,
'projects' => $projects
);
return View::make('users.profile', $data);
}