Display Images From Storage Folder in View - laravel

When I upload images to a storage folder in my localhost, it works fine. However, when I move my Laravel 5.7 project to shared hosting the images don't appear, and I don't know why.
Thank you for your help.
Blade
#foreach ($data as $user)
#foreach(json_decode($user->name, true) as $images)
#endforeach
#endforeach
<!-- Wrapper for slides -->
<div class="carousel-inner">
#foreach ($data as $user)
#foreach(json_decode($user->name, true) as $images)
<div class="item">
<img src="{{ asset('/slider/images') }}/{{$images}}" alt="Los Angeles" style="width:100%;">
</div>
#endforeach
#endforeach
</div>
Controller
<?php
if ($request->hasfile('image')) {
foreach ($request->file('image') as $image) {
$name = $image->getClientOriginalName();
$image->move(storage_path() . '/slider/images/', $name);
$data[] = $name;
}
$query = DB::table('slider')->insert([
['title' => 'lorem', 'alt' => 'lorem', 'name' => json_encode($data)],
]);
return "good";
} else {
return "null";
}

https://stackoverflow.com/a/50771337/3240068
Your shared hosting server may or may not allow symlinks. If you run the command and it still does not work, then you have two options, basically.
1) Upload / move / copy images from storage to public;
2) https://laravel.com/docs/5.7/responses#file-downloads
Create a route and controller that reads and returns images from storage. This is not tested, so do some proof-reading and research, but it should go something like this:
// Route
Route::get('storage-asset/{$path}', 'App\Http\SomeController#getStorageAsset');
// Controller
public function getStorageAsset($path)
{
if (File::exists(storage_path($path)) {
return response()->file(storage_path($path));
}
// If file not found.
return abort(404)
}

Please try login using ssh and run
php artisan storage:link
or create .htaccess to your root laravel folder and add this code below.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^(.*)$ public/$1 [L]
</IfModule>
and make sure you have proper permission to your storage folder.
that could probably helps.

You need to create a file (e.g, link.php) inside the public folder and declare the codes below.
make sure to declare your path as is in your app.
<?php
symlink('../public_html/storage/app/public', '../public_html/public/storage');
then, you can visit your-domain.com/link.php, and that's it. done

Related

Laravel 9 Livewire The photo failed to upload

I started learning Laravel 9 livewire. I am trying to make an image upload application. I did the exact example in the Livewire documentation, but I get an error that the image could not be uploaded. When I do the same application on my mac computer, it works without any problems. It doesn't work when I do it on my windows computer.
ImageUpload.php
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use Livewire\WithFileUploads;
class ImegaUpload extends Component
{
use WithFileUploads;
public $photo;
public function save()
{
$this->validate([
'photo' => 'image|max:1024', // 1MB Max
]);
$this->photo->store('photos');
}
public function render()
{
return view('livewire.imega-upload');
}
}
image-upload.blade.php
<div>
<h1>Image upload</h1>
<form wire:submit.prevent="save">
<input type="file" wire:model="photo">
#error('photo')
<span class="error">{{ $message }}</span>
#enderror
<button type="submit">Save Photo</button>
</form>
</div>
Error
I'm doing the example in the Livewire documentation but still getting the error. Not even the livewire-temp folder is created.
Look like your PHP.ini is missing
sys_temp_dir
and
upload_tmp_dir
uncomment and then set its value.
mine example.
Laragon on win 10:
sys_temp_dir = "c\laragon\tmp"
upload_tmp_dir = "c\laragon\tmp"
all temp files will go to that location (not just uploaded)
In
App\Http\Middleware\TrustProxies
change
protected $proxies;
to
protected $proxies = '*';
it helped me

Laravel protect audio file from direct url and show on blade view

I have a form with uploading audio mp3.
I need to protect these audio files from direct access from url, accessible only logged users.
Added a new storage disk in > filesystem.php
'audio' => [
'driver' => 'local',
'root' => storage_path('app/private/audio/'),
],
Added a new route in > web.php
Route::get('/private/audio/{audio}', [AudioController::class, 'index']);
AudioController
public function __construct()
{
$this->middleware('auth');
}
public function index($audio)
{
$path = "/private/audio/{$audio}";
if(Storage::exists($path)) {
return Storage::download($path);
}
abort(401);
}
Now if i get on follow url, my audio will download only for logged users, so works fine.
https://example.com/private/audio/my_audio_file.mp3
So how can I access to audio file in a blade view for logged users only.
#foreach($files as $file)
<audio preload="none" src="{{ asset('audio/private/') }}/{{ $file->file_name }}.mp3" controlslist="nodownload" type="audio/mp3">
</audio>
#endoforeach
Is there a way for get this?
It works fine after doing the optimize command:
php artisan optimize
#foreach($files as $file)
#if(Auth::check())
<audio preload="none" src="{{ asset('audio/private/') }}/{{ $file->file_name }}.mp3" controlslist="nodownload" type="audio/mp3"></audio>
#else
Login to access audio
#endif
#endforeach

laravel local storage 404 error on images

I have made a youtube style website, some people may click the video to be private, I keep these videos in storage/app/vidoes/{channelname}, the public images and videos I have working not a problem but local storage I am having a problem with, any ideas?
just getting a 404 on the thumbnails
thanks
view
<img src="{{ route('home.image', ['file_path' => 'videos/' . $video->channel_name . '/thumbnails/' . $video->video_thumbnail_name]) }}" alt="" class="img-responsive">
route
Route::get('{file_path}', [
'uses' => 'HomeController#getImage',
'as' => 'home.image'
]);
controller
public function getImage($filepath)
{
$fileContents = \Storage::disk('local')->get($filepath);
$response = \Response::make($fileContents, 200);
$response->header('Content-Type', "image/jpg");
return $response;
}
Laravel 5.8 local storage working for images
view
<img class="home-video" src="{{ route('getImage', ['thumbnail' => $video->video_thumbnail_name, 'channel_name' => $video->channel_name]) }}" alt="" >
Route
Route::get('get-image/{channel_name}/{thumbnail}','HomeController#getImage')->name('getImage');
Controller
public function getImage($channel_name,$thumbnail)
{
$fileContents = \Storage::disk('local')->get("videos/$channel_name/thumbnails/$thumbnail");
return \Image::make($fileContents)->response();
}
see how the thumbnail is important for me, I was passing the thumbnail name eg photo.jpg if you are using route model binding you would want to pass the id of the image, hope this saves someone a few hours

Laravel5.2 delete doesn't work

I developed website with CRUD on products table .this is the structure of the table.
Create and update works fine But delete not work.
This is the form in blade to delete product
{{ Form::open(array('url' => 'admin/products/' . $product->id, 'class' => 'pull-right')) }}
{{ Form::hidden('_method', 'DELETE') }}
{{ Form::submit('Delete ', array('class' => 'btn btn-warning')) }}
{{ Form::close() }}
And this the destroy function in controller
public function destroy($id)
{
$product = Product::find($id);
$product->delete();
// Product::destroy($id);
return redirect('admin/products')->with('message', 'Successfully deleted the product!');
}
And This is my routes
Route::group(['middleware' =>'App\Http\Middleware\AdminMiddleware'], function () {
//resource
Route::resource('admin/products','AdminFront');
});
When I click delete button it enter the destroy function and dd($id) correct
But when write
$product = Product::find($id);
$product->delete();
Or
Product::destroy($id);
I get this error
The localhost page isn’t working
localhost is currently unable to handle this request.
This error tired me . I developed delete fun with resource API in another table and work fine.I don't know are the problem in the db or where. please any one help me ,
What does your routes.php look like?
You may need to include the resource route in routes.php.
Route::resource('admin/products/', 'TheNameOfYourController');
But make sure the route is protected either in the controller or routes.php.
Here is somewhat the same setup you have:
https://github.com/jeremykenedy/laravel-material-design/blob/master/app/Http/routes.php LINE 119
https://github.com/jeremykenedy/laravel-material-design/blob/master/app/Http/Controllers/UsersManagementController.php LINES 369-376
https://github.com/jeremykenedy/laravel-material-design/blob/master/resources/views/admin/edit-user.blade.php LINES 243-246
Cheers!

NotFoundHttpException Laravel

I am very new in learning Laravel. I want to fetch data from a database and show it. I can do it. But I want to use the title (fetched from the database) as a link. but then I get a NotFoundHttpException.
Routes
Route::get('articles', 'ArticleController#index');
Route::get('articles/{id}', 'ArticleController#show');
Controller
class ArticleController extends Controller
{
public function index()
{
$articles = Article::all();
return view('articles.index', compact('articles'));
}
public function show($id){
$article = Article::find($id);
return view('articles.show', compact('article'));
}
}
View
#extends('new_welcome')
#section('content')
<h1>Articles</h1>
#foreach($articles as $article)
<article>
<h2>
{{$article->title}}
</h2>
<div class="body">{{ $article->body}}</div>
</article>
#endforeach
#stop
Can someone help me in this case?
Your problem is because of You've "eat" one curly brace (blade engine skips it):
was:
href="{url ('/articles',$article->id)}"
have to be:
href="{{url ('/articles',$article->id)}}"
as You said:
if I click on any single article title then it can not show me the
specific article. But, if I give the URL "homestead.app/articles/2";
so You can see that when You click on link Your browser's address bar becomes:
homestead.app/{url ('/articles',$article->id)}
Because You're beginner so I'll give You advice to not to set direct url in views using url() helper.
Named routes are better if You want to have app that will work properly if in future You decide to change url from: articles to artcls. In this named routes will save You from bulk changing urls in view files.
set name to Your route using 'as' directive that makes Your routing flexible for changes (when You need to change URL so You change only path and keep views unchanged):
Route::get('articles/{id}', ['as' => 'article', 'uses' => 'ArticleController#show']);
Route::get('articles', ['as' => 'articles', 'uses' => 'ArticleController#index']);
change Your view file (find route helper in href):
#extends('new_welcome')
#section('content')
<h1> Articles </h1>
#foreach($articles as $article)
<article>
<h2>
{{$article->title}}
</h2>
<div class="body">{{ $article->body}}</div>
</article>
#endforeach
#stop

Resources