Images from my storage uploads are not showing PHP Laravel - php

After setting up my profile page my uploaded images initially produced an image on my local host. However lately it shows up as an icon instead https://i.stack.imgur.com/pp0Yt.png
I should note I am using php 7.3.19
profiles/index.blade.php
<div class="container">
<div class="row">
<div class="col-3 p-5">
<img src="{{ $user->profile->profileImage() }}" class="rounded-circle w-100">
</div>
<div class="col-9 pt-5">
<div class="d-flex justify-content-between align-items-baseline">
<div class="d-flex align-items-center pb-3">
<div class="h4">{{ $user->username }}</div>
<follow-button user-id="{{ $user->id }}" follows="{{ $follows }}"></follow-button>
</div>
#can('update', $user->profile)
Add New Post
#endcan
</div>
#can('update', $user->profile)
Edit Profile
#endcan
<div class="d-flex">
<div class="pr-5"><strong>{{ $postCount }}</strong> posts</div>
<div class="pr-5"><strong>{{ $followersCount }}</strong> followers</div>
<div class="pr-5"><strong>{{ $followingCount }}</strong> following</div>
</div>
<div class="pt-4 font-weight-bold">{{ $user->profile->title }}</div>
<div>{{ $user->profile->description }}</div>
<div>{{ $user->profile->url }}</div>
</div>
</div>
<div class="row pt-5">
#foreach($user->posts as $post)
<div class="col-4 pb-4">
<a href="/p/{{ $post->id }}">
<img src="/storage/{{ $post->image }}" class="w-100">
</a>
</div>
#endforeach
</div>
</div>
#endsection
Is there an issue in the way I am picking it up from the storage?
I used 'php artisan storage:link'
create.blade.php
<div class="container">
<form action="/p" enctype="multipart/form-data" method="post">
#csrf
<div class="row">
<div class="col-8 offset-2">
<div class="row">
<h1>Add New Image</h1>
</div>
<div class="form-group row">
<label for="caption" class="col-md-4 col-form-label">Post Caption</label>
<input id="caption"
type="text"
class="form-control{{ $errors->has('caption') ? ' is-invalid' : '' }}"
name="caption"
value="{{ old('caption') }}"
autocomplete="caption" autofocus>
#if ($errors->has('caption'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('caption') }}</strong>
</span>
#endif
</div>
<div class="row">
<label for="image" class="col-md-4 col-form-label">Post Image</label>
<input type="file" class="form-control-file" id="image" name="image">
#if ($errors->has('image'))
<strong>{{ $errors->first('image') }}</strong>
#endif
</div>
<div class="row pt-4">
<button class="btn btn-primary">Add New Post</button>
</div>
</div>
</div>
</form>
</div>
#endsection
PostsController.php
<?php
namespace App\Http\Controllers;
use App\Post;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;
class PostsController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$users = auth()->user()->following()->pluck('profiles.user_id');
$posts = Post::whereIn('user_id', $users)->with('user')->latest()->paginate(5);
return view('posts.index', compact('posts'));
}
public function create()
{
return view('posts.create');
}
public function store()
{
$data = request()->validate([
'caption' => 'required',
'image' => ['required', 'image'],
]);
$imagePath = request('image')->store('uploads', 'public');
$image = Image::make(public_path("storage/{$imagePath}"))->fit(1200, 1200);
$image->save();
auth()->user()->posts()->create([
'caption' => $data['caption'],
'image' => $imagePath,
]);
return redirect('/profile/' . auth()->user()->id);
}
public function show(\App\Post $post)
{
return view('posts.show', compact('post'));
}
}
ProfilesController.php
<?php
namespace App\Http\Controllers;
use App\Profile;
use App\User;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\Cache;
class ProfilesController extends Controller
{
public function index(User $user)
{
$follows = (auth()->user()) ? auth()->user()->following->contains($user->id) : false;
$postCount = Cache::remember(
'count.posts.' . $user->id,
now()->addSeconds(30),
function () use ($user) {
return $user->posts->count();
});
$followersCount = Cache::remember(
'count.followers.' . $user->id,
now()->addSeconds(30),
function () use ($user) {
return $user->profile->followers->count();
});
$followingCount = Cache::remember(
'count.following.' . $user->id,
now()->addSeconds(30),
function () use ($user) {
return $user->following->count();
});
return view('profiles.index', compact('user', 'follows', 'postCount', 'followersCount', 'followingCount'));
}
//($user = (User::findOrFail($user));)
//('user' => $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('image')) {
$imagePath = request('image')->store('profile', 'public');
$image = Image::make(public_path("storage/{$imagePath}"))->fit(1000, 1000);
$image->save();
$imageArray = ['image' => $imagePath];
}
auth()->user()->profile->update(array_merge(
$data,
$imageArray ?? []
));
return redirect("/profile/{$user->id}");
}
public function show($user_id)
{
$user = User::find(1);
$user_profile = Profile::info($user_id)->first();
return view('profiles.show', compact('profile', 'user'));
}
public function profile()
{
return $this->hasOne('Profile');
}
}

Use asset helper function to get the uploaded image URL.
<img src="{{ asset('storage/' . $post->image) }}" class="w-100">
OR
<img src="{{ asset(Storage::url($post->image)) }}" class="w-100">

Related

Function Show CRUD not working in Controller.php

I'm using laravel 8 for CRUD.. i try using create and store function in controller and it's perfecly fine then the data will store in database. Now, i try to use show function which the data that i created will show to user once they click the 'show' button. The most error i found is undefined $product
here is my blade for index.blade
<a class="btn btn-info" href="show-index">Show</a>
Here is my blade for show.blade.php
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2> Show Product</h2>
</div>
<div class="pull-right">
<a class="btn btn-primary" href="pro_index"> Back</a
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Name:</strong>
{{ $product->name }}
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Details:</strong>
{{ $product->detail }}
</div>
</div>
</div>
Here is my ProductController.php
class ProductController extends Controller
{
public function index()
{
$products = Product::all();
return view('products.pro_index',compact('products'));
}
public function create()
{
return view('products.create');
{
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'detail' => 'required',
]);
$product= Product::create([
'name' => $request->name,
'detail' => $request->detail,
]);
return redirect('/pro_index') ->with('success','Your record has been updated');
}
public function show (Product $product)
{
$product = Product::find($product);
return view('products.show');
}
}
here is my web.php
Route::get('/show-index', [App\Http\Controllers\ProductController::class, 'show'])->name('show');
You don't need this line of code because you already have model binding in place
$product = Product::find($product);
Change anchor href from href="show-index" to href="{{ route('show', $product) }}
In controller
public function show (Product $product)
{
return view('products.show', compact('product'));
}
in web.php
Route::get('/show/{product}', [App\Http\Controllers\ProductController::class, 'show'])
->name('show');
For more : https://laravel.com/docs/8.x/routing#route-model-binding

Larvel Update and Destroy route not working [duplicate]

This question already has answers here:
How to make a delete request with Laravel
(2 answers)
Closed 2 years ago.
The accept button has the route route('members.update', $member->id)
The deny button has the route route('members.destroy', $member->id)
These are the cards:
#foreach ($members as $member)
<div class="my-1 px-1 w-full md:w-1/2 lg:my-4 lg:px-4 lg:w-1/3">
<article class="bg-white overflow-hidden rounded-lg shadow-lg">
<div class="flex items-center justify-between leading-tight p-2 md:p-4 w-max">
<div class="w-1/2">
<small class="text-gray-600">Full name:</small>
<h1 class="text-lg pr-2"> {{ $member->firstname }} {{ $member->lastname }} </h1>
</div>
<div class="w-1/2">
<small class="text-gray-600">Birthdate:</small>
<h1 class="text-lg">{{ date('d-m-Y', strtotime($member->birthdate)) }}</h1>
</div>
</div>
<div class="flex items-center justify-between leading-tight p-2 md:p-4">
<div class="w-1/2">
<small class="text-gray-600">Student id:</small>
<h1 class="text-lg pr-2">{{ $member->studentid }}</h1>
</div>
<div class="w-1/2">
<small class="text-gray-600">Discord:</small>
<h1 class="text-lg">{{ $member->discordname }}{{ $member->discordtag }}</h1>
</div>
</div>
<footer class="flex items-center leading-tight p-2 md:p-4 justify-start">
<form method="PATCH" action="{{ route('members.update', $member->id) }}">
#method('PATCH')
<button class="bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded mr-2">Accept</button>
#csrf
</form>
<form method="DELETE" action="{{ route('members.destroy', $member->id) }}">
#method('DELETE')
<button class="bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded">Deny</button>
#csrf
</form>
</footer>
</article>
</div>
#endforeach
And this is my controller:
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\Member;
use Illuminate\Http\Request;
class MemberController extends Controller {
public function index() {
$members = Member::where(['status' => false])->get();
return view('dashboard')->with(['members' => $members]);
}
public function show($id) {
$members = Member::where(['id' => $id])->get();
return view('dashboard')->with(['members' => $members]);
}
public function store(Request $request) {
$validatedData = $request->validate([
'firstname' => 'required|max:255|alpha|min:2',
'lastname' => 'required|max:255|alpha|min:2',
'studentid' => 'required|integer|alpha_num',
'birthdate' => 'required|date',
'discordname' => 'required|max:255',
'discordtag' => 'required|max:255|size:5'
]);
$member = new Member;
$member->firstname = $request->firstname;
$member->lastname = $request->lastname;
$member->studentid = $request->studentid;
$member->birthdate = $request->birthdate;
$member->discordname = $request->discordname;
$member->discordtag = $request->discordtag;
$member->status = false;
$member->save();
return \redirect()->route('index');
}
public function update($id) {
die;
$member = Member::find($id);
$member->status = 1;
$member->save();
return \redirect()->route('dashboard');
}
/**
* TODO - SEND EMAIL ON DELETE
*
* #return void
*/
public function destroy($id) {
DB::delete('delete members where id = ?', [$id]);
}
public function accepted($id) {
update($id);
}
}
My routes:
When i click the accept or deny button it sends me to this link: http://hit.localhost.nl/members/3?_method=PATCH&_token=0g5odDLEKCicceDOf4EuPMGIB1X95cwWHGMxMqcR
And runs the show() function instead of the update or destroy functions. What am i doing wrong here?
method="PATCH" and method="DELETE" don't exist, just get, post and dialog. Change both of those to method="post".

Image is not shwing in the user profile in Laravel

I am having a little problem here. I am trying to put an image in my User Profile. The image is saved in the database and no errors are shown up, but I never see the default image that I gave to it. It says that it's there but The place for the pic stays empty.
This is what I've got for now:
UserController.php
<?php
namespace app\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
// namespace App\Http\Controllers\Controller;
// use App\Http\Requests\Request;
// use Illuminate\Http\Request;
class UserController extends Controller
{
public function profile()
{
$user = Auth::user();
return view('profile',compact('user',$user));
}
public function update_avatar(Request $request){
$request->validate([
'avatar' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$user = Auth::user();
$avatarName = $user->id.'_avatar'.time().'.'.request()->avatar->getClientOriginalExtension();
$request->avatar->storeAs('avatars',$avatarName);
$user->avatar = $avatarName;
$user->save();
return back()
->with('success','You have successfully upload image.');
}
/** Return view to upload file */
public function uploadFile(){
return view('uploadfile');
}
/** Example of File Upload */
public function uploadFilePost(Request $request){
$request->validate([
'fileToUpload' => 'required|file|max:1024',
]);
$request->fileToUpload->store('logos');
return back()
->with('success','You have successfully upload image.');
}
}
profile.blade.pbp
<hidden='Illuminate\Support\Facades\Auth'>
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
#if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>{{ $message }}</strong>
</div>
#endif
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
</div>
<div class="row justify-content-center">
<div class="profile-header-container">
<div class="profile-header-img">
<img class="rounded-circle" width="150" height="150" src="/storage/avatars/{{ $user->avatar }}" />
<!-- badge -->
<div class="rank-label-container">
<span class="label label-default rank-label">{{$user->name}}</span>
</div>
</div>
</div>
</div>
<div class="row justify-content-center">
<form action="/profile" method="post" enctype="multipart/form-data">
#csrf
<div class="form-group">
<input type="file" class="form-control-file" name="avatar" id="avatarFile" aria-describedby="fileHelp">
<small id="fileHelp" class="form-text text-muted">Please upload a valid image file. Size of image should not be more than 2MB.</small>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
#endsection
filesystems.php
'default' => env('FILESYSTEM_DRIVER', 'public'),
How can I make the default avatar visible?
Also, do you have any suggestions on how to put a watermark on the photos that will appear each time someone uploads photos?
Thanks in advance!
You can try this. First execute this command
php artisan storage:link
Then
<img class="rounded-circle" width="150" height="150" src="{{url('')}}/storage/avatars/{{ $user->avatar }}"/>

How can I get a single category of question in a quiz app using Laravel Eloquent

I want to select a single category of questions that the user can select with options. I have tried doing this with a resource I found online.
The category page:
#foreach($categories as $category)
<section>
<a href="#" class="image">
<img src="{{asset('images/pic09.jpg')}}" alt="" data-position="top center" />
</a>
<div class="content">
<div class="inner">
<header class="major">
<h3>{{$category->name}}</h3>
</header>
<p></p>
<ul class="actions">
<li>Learn more</li>
</ul>
</div>
</div>
</section>
#endforeach
Here is the TestController I'm using, the show controller is might to select questions and options with the category_id at random:
namespace App\Http\Controllers;
use App\Category;
use App\Http\Requests\StoreTestRequest;
use App\Option;
class TestsController extends Controller
{
public function show($id)
{
$categories = Category::find($id)->with(
['categoryQuestions' => function ($query) {
$query->inRandomOrder()
->with(
['questionOptions' => function ($query) {
$query->inRandomOrder();
}]
);
}]
)
->whereHas('categoryQuestions')
->get();
return view('client.test', compact('categories'));
}
public function store(StoreTestRequest $request)
{
$options = Option::find(array_values($request->input('questions')));
$result = auth()->user()->userResults()->create(
[
'total_points' => $options->sum('points')
]
);
$questions = $options->mapWithKeys(
function ($option) {
return [$option->question_id => [
'option_id' => $option->id,
'points' => $option->points
]
];
}
)->toArray();
$result->questions()->sync($questions);
return redirect()->route('client.results.show', $result->id);
}
}
web.php
// User
Route::group(['as' => 'client.', 'middleware' => ['auth']], function () {
Route::get('home', 'HomeController#redirect');
Route::get('dashboard', 'HomeController#index')->name('home');
Route::resource('/test', 'TestsController');
Route::get('results/{result_id}', 'ResultsController#show')->name('results.show');
Route::get('send/{result_id}', 'ResultsController#send')->name('results.send');
});
This is the Blade file from the resource I'm using:
#extends('layouts.home')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Test</div>
<div class="card-body">
#if(session('status'))
<div class="row">
<div class="col-12">
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
</div>
</div>
#endif
<form method="POST" action="{{ route('client.test.store') }}">
#csrf
#foreach($categories as $category)
<div class="card mb-3">
<div class="card-header">{{ $category->name }}</div>
<div class="card-body">
#foreach($category->categoryQuestions as $question)
<div class="card #if(!$loop->last)mb-3 #endif">
<div class="card-header">{{ $question->question_text }}</div>
<div class="card-body">
<input type="hidden" name="questions[{{ $question->id }}]" value="">
#foreach($question->questionOptions as $option)
<div class="form-check">
<input class="form-check-input" type="radio" name="questions[{{ $question->id }}]" id="option-{{ $option->id }}" value="{{ $option->id }}"#if(old("questions.$question->id") == $option->id) checked #endif>
<label class="form-check-label" for="option-{{ $option->id }}">
{{ $option->option_text }}
</label>
</div>
#endforeach
#if($errors->has("questions.$question->id"))
<span style="margin-top: .25rem; font-size: 80%; color: #e3342f;" role="alert">
<strong>{{ $errors->first("questions.$question->id") }}</strong>
</span>
#endif
</div>
</div>
#endforeach
</div>
</div>
#endforeach
<div class="form-group row mb-0">
<div class="col-md-6">
<button type="submit" class="btn btn-primary">
Submit
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
How can the Testcontroller be made to select questions and answer from a single category and save the result from the user's answers?
public function index()
{
$questions = Category::select('categories.name', 'question_result.points')
->join('questions', 'categories.id', '=', 'questions.category_id')
->join('question_result', 'questions.id', '=', 'question_result.question_id')
->join('results', 'question_result.result_id', '=', 'results.id')
->where('results.user_id', auth()->id())
->get();
return view('client.home', compact('questions'));
}

How do i save the file name/image through my database?

Im currently doing the file upload. I searched through the internet regarding the file upload. The website that I saw is only saving through the images folder, i tried to put the Administrator::create(['image' => $request->image]);
It saved to the database but its not the name of the image that i upload.. The name of the image after i-upload C:\xampp\tmp\php306A.tmp
My Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Administrator;
class ImageController extends Controller
{
/**
* Create view file
*
* #return void
*/
public function imageUpload()
{
return view('image-upload');
}
/**
* Manage Post Request
*
* #return void
*/
public function imageUploadPost(Request $request)
{
$file = $request->file('image');
$this->validate($request, [
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$imageName = time().'.'.$request->image->getClientOriginalExtension();
$request->image->move(public_path('images'), $imageName);
// Administrator::create($request->all());
Administrator::create([
'image' => $request->image
]);
return back()
->with('success','Image Uploaded successfully.')
->with('path',$imageName);
}
}
?>
My View
<!DOCTYPE html>
<html>
<head>
<title>Laravel 5.3 Image Upload with Validation example</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="panel panel-primary">
<div class="panel-heading"><h2>Laravel 5.3 Image Upload with Validation example</h2></div>
<div class="panel-body">
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
#if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>{{ $message }}</strong>
</div>
<img src="/images/{{ Session::get('path') }}">
#endif
<form action="{{ url('image-upload') }}" enctype="multipart/form-data" method="POST">
{{ csrf_field() }}
<div class="row">
<div class="col-md-12">
<input type="file" name="image" />
</div>
<div class="col-md-12">
<button type="submit" class="btn btn-success">Upload</button>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
My Routes
Route::get('image-upload','ImageController#imageUpload');
Route::post('image-upload','ImageController#imageUploadPost');
My model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Administrator extends Model
{
protected $table = 'accounts';
protected $fillable = array(
'first_name',
'middle_name',
'last_name',
'email',
'image',
''
);
}
To get the uploaded image, you could change these lines:
$imageName = time().'.'.$request->image->getClientOriginalExtension();
$request->image->move(public_path('images'), $imageName);
to
$imageName = "";
if($request->hasFile('images')) {
$image = $request->file('images');
$imageName = time() . '.' . $image->getClientOriginalExtension();
$image->move(public_path('images'), $imageName);
}
And your create part:
Administrator::create([
'image' => $imageName
]);
view part
{!! Form::open(array('url'=>'insertfile','method'=>'POST' ,'class'=>'form-horizontal','files'=>true)) !!}
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label class="control-label col-sm-2" for="pwd">Upload:</label>
<div class="col-sm-4">
<input type="file" name="filenam" class="filename">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
{!! Form::close() !!}
controller
public function insertFile(){
$file= Input::file('filenam');
$rules = array('file' => 'required|max:10000|mimes:jpeg,png,jpg,gif,svg,csv,xls,xlsx,doc,docx,pdf');
$validator = Validator::make(array('file'=> $file), $rules);
if($validator->passes()){
$destinationPath = 'up_file';
$filename = $file->getClientOriginalName();
$data=array(
'file_name' => $filename,
);
var_dump($data);
yourmodelname::insert($data);
$upload_success = $file->move($destinationPath, $filename);
}
}
in route:
Route::get('/uploadfile','UploadController#getView');
Route::post('/insertfile','UploadController#insertFile');
file will be upload in yourproject/public/up_file directory

Categories