I tried uploading the file via Laravel Livewire using Livewire\WithFileUploads and I tried to get the preview of the image selected, to be uploaded, by implementing the method shown in the official documentation of livewire, but inspite of doing exactly the same I don't get to see the preview.
What I get to see is
Broken Image as preview
I also tried to inspect the element and get the url and the URL I got was
http://192.168.1.33:8000/livewire/preview-file/tmRlboRMpPEv3MMOiX5iu6vPph0PLC-metacHJvZmlsZXBpYy5qcGc=-.jpg?expires=1654720661&signature=e0d825c78ae9bcbc8123b72a542ba827d984810aa32dee8527e63e0c9babf27a
I tried opening this URL and got to see A big black screen with a grey square in center
I am not sure where am I going wrong here. I am quickly adding up controller, blade and config, hoping that I get some solution for it, as I also referred to this solution but it didn't help
Livewire Controller
use Livewire\Component;
use Livewire\WithFileUploads;
class CenterRegistration extends Component
{
use WithFileUploads;
public $logo;
public function updated($propertyName)
{
$this->validateOnly($propertyName);
}
public function render()
{
return view('livewire.logo-uploader');
}
public function submit()
{
$this->validate();
}
protected function rules()
{
return [
'logo' => [
'required',
'mimes:png,jpg',
'max:2048',
],
];
}
}
Livewire Blade
<form wire:submit.prevent="submit">
<div class="input-group shadow-sm">
<div class="input-group-prepend input-group-text bg-light rounded-5">
{{ Form::label('logo','Logo',[
'for' => 'logo',
'class' => 'rounded-0 required',
]) }}
</div>
{{ Form::file('logo',[
'id' => 'logo',
'class' => "form-control rounded-5",
'accept' => 'image/*',
'required',
'wire:model' => "logo"
]) }}
</div>
#if ($logo)
<div>
<img src="{{ $logo->temporaryUrl() }}"/>
</div>
#endif
#error('logo') <span class="error text-danger">{{ $message }}</span> #enderror
<button class="btn btn-primary rounded-pill text-center mt-3" style="width: 20%;" type="submit">submit</button>
</form>
Basic Info
Laravel : 9.17.0 | Xampp
Check your storage folder permission
composer update
chmod -R 777 storage
chmod -R 777 public/storage
chmod -R 777 bootstrap/cache
php artisan optimize:clear
php artisan optimize
Related
I'm using Laravel with TailwindCSS, so I assume that, the SweetAlert wouldn't work.
I'm also using Livewire Powergrid, which works fine, but I don't know how to emit simple alert window after clicking f.e. "Delete" button.
Inside actions method, there's option emit() but I really don't know what it does.
Button::make('destroy', 'Delete')
->class('bg-red-500 cursor-pointer text-white px-3 m-1 rounded text-sm hover:bg-red-800')
->emit(),
What does it call and where? Should I put emited method inside UsersTable(powergrid component) or somewhere else?
Can someone explain? There's other possibility to achieve the alert window with confirmation?
You have to pass the method name within emit and that method has to be defined in the same class (I am using PowerGrid Component), example :
// rowActionEvent is my method name and the second parameter is data array which has to be passes ad parameter to rowActionEvent method
Button::make('destroy', 'Delete')
->class('bg-red-500 cursor-pointer text-white px-3 m-1 rounded text-sm hover:bg-red-800')
->emit('rowActionEvent', ['id' => 'id']),
In the same class, define the method also
protected function getListeners()
{
return array_merge(
parent::getListeners(),
[
'rowActionEvent',
]);
}
public function rowActionEvent(array $data): void
{
$message = 'You have clicked #' . $data['id'];
$this->dispatchBrowserEvent('showAlert', ['message' => $message]);
}
In the frontend (blade file or the view file) define the showAlert javascript.
<script>
window.addEventListener('showAlert', event => {
alert(event.detail.message);
})
</script>
In my case , I had to add both the event and the listener to the mother component , instead of the PowerGrid class (cause it was not working )
Inside Powergrid class (UserTable) , I have these buttons inside actions function
public function actions(): array
{
return [
Button::make('edit', 'Edit')
->class('btn btn-info')
->route('admin.users.edit', ['userId' => 'id']),
Button::make('destroy', 'Delete')
->class('btn btn-danger')
->emit('deleteUser', ['key' => 'id']),
];
}
Livewire Mother Component
class Users extends Component
{
public $userId ;
use LivewireAlert;
protected $listeners = ['deleteUser' , 'confirmDelete'];
public function deleteUser($userId){
$this->userId = $userId['userId'];
$this->alert('warning', 'Are you sure , you want to delete this user ? ' , [
'icon'=>'warning',
'showConfirmButton' => true,
'showCancelButton' => true,
'confirmButtonText' => 'Delete',
'cancelButtonText' => 'Cancel',
'onConfirmed' => 'confirmed',
'allowOutsideClick' => false,
'timer' => null ,
'position' => 'center',
'onConfirmed' => 'confirmDelete'
]);
}
Public function confirmDelete(){
Admin::destroy($this->userId);
$this->flash('success', 'User Successfully deleted', [
'position' => 'center',
'timer' => 3000,
'toast' => false,
'icon' => 'success',
], '/admin/users');
}
public function render()
{
return view('livewire.admin.users')->layout('layouts.admin.admin-template');
}
}
Livewire Mother Component Blade
<div>
<div class="row mb-2">
<div class="col-6 d-flex align-items-center">
<h3 class="mb-0">Users {{ $userId }}</h3>
</div>
<div class="col-6 text-end">
<a class="btn bg-gradient-dark mb-0" href="{{
route('admin.users.create') }}"><i class="fas fa-plus"></i> Add
New User</a>
</div>
</div>
<div class="col mb-3">
<div class="card">
<div class="card-body p-3">
<livewire:admin-table/>
</div>
</div>
</div>
</div>
sample image 1
I used Livewire Alert package
I'm creating a shop, with an upload image in Laravel 9.
Everything is on my database, and my image is sent on file storage/app/public/nameofthefile/nameoftheimage.png.
But my image does not appear on my website like this :
As you can see on the console, the image has the correct direction I give you the code of my controller, my html page :
My CONTROLLER :
public function CreateArticleAction(Request $request) {
$request->validate([
'nom' => ['required'],
'description' => ['required'],
'prix' => ['required'],
'quantité' => ['required'],
'img' => ["required", "image", "mimes:jpg,jpeg,png,gif,svg,webp", "max:2048"],
]);
$path = $request->file('img')->store('boutique-storage', 'public');
$iduser = Session::get('iduser');
$article = new Boutique();
$article->iduser = $iduser;
$article->nom = request('nom');
$article->description = request('description');
$article->prix = request('prix');
$article->quantité = request('quantité');
$article->img = $path;
$article->save();
return redirect('/boutique');
}
My HTML page :
#foreach ($boutiques as $boutique)
<div class="produit">
<img src="{{ asset('storage/app/public/' . $boutique->img) }}" alt="Produit" class="img-produit" />
<p>{{ $boutique->nom }}</p>
<p>{{ $boutique->description }}</p>
<p>{{ $boutique->prix }}</p>
<p>{{ $boutique->quantité }}</p>
<div>
<a class="text-danger" href="/delete-article/{{ $boutique->idproduit }}">Supprimer</a>
<a class="text-primary" href="/FormUpdate/{{ $boutique->idproduit }}">Modifier</a>
</div>
</div>
#endforeach
And the DIRECTION :
I think you can see everything is ok, each data is sent correctly on the database but why my image does not appear ??
Thanks a lot !
Try run this command
php artisan storage:link
Ah ok so I forgot to add this on .env file : FILESYSTEM_DISK=public
Now with the command php artisan storage:link it works :D
replace
<img src="{{ asset('storage/app/public/' . $boutique->img) }}"
with
<img src="{{ asset($boutique->img) }}"
When I try to use the localization and retrieve translation strings, Laravel for some reason throws: .
From the controller to the view (products index page), I pass the $products variable. On that page, I use the translation string {{ __('Products') }} and getting htmlspecialchars() error. As I understood it, translation string for some reason thinks that I passing $products variable to {{ __('Products') }} translation string, because if I change translation string to (for example) {{ __('Products page') }}, I not getting this error anymore. Can someone explain, why this error is occurring?
Controller
Code when an error is occurring
Code when an error no more occurring
UPDATE
Fixed problem when added en.json file in the lang folder.
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\Localization::class,
],
you add this created middleware to the list and then you go to the web.php routes file and add
Route::get('/locale/{locale}', function ($locale){
\Session::put('locale', $locale);
return redirect()->back();
})->name('traduction');
et ensuite vous pouvez récupérer la session de cette facon
<a href="{{route('traduction',['locale'=>'en'])}}" class="menu-link d-flex px-5 active">
<a href="{{route('traduction',['locale'=>'fr'])}}" class="menu-link d-flex px-5 active">
in case you want to display an image according to the session
<a href="#" class="menu-link px-5">
<span class="menu-title position-relative">Langue {{ Session::get('locale') }}
#if (Session::get('locale') == "fr")
<span class="fs-8 rounded bg-light px-3 py-2 position-absolute translate-middle-y top-50 end-0">Francais
<img class="w-15px h-15px rounded-1 ms-2" src="assets/media/flags/france.svg" alt="" /></span></span>
#else
<span class="fs-8 rounded bg-light px-3 py-2 position-absolute translate-middle-y top-50 end-0">English
<img class="w-15px h-15px rounded-1 ms-2" src="assets/media/flags/united-states.svg" alt="" /></span></span>
#endif
</a>
sorry but you have to use both answers as they are complementary
in truth to translate i don't do it that way. in fact i create a midleware and i create a fair route. let's take the case of french and english. let's create a midleware Location
php artisan make:middleware Localisation
then fill in the middleware
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class Localization
{
public function handle(Request $request, Closure $next)
{
if(\Session::has('locale'))
{
\App::setlocale(\Session::get('locale'));
}
return $next($request);
}
}
in laravel, i have to link the storage using php artisan storage:link so i can show the image that when user to post a article with a image, the image will be shown. but for now, the image didn't show up. How do i fix it.
here's the code from views/post/index.blade.php
<tbody>
#foreach($posts as $post)
<tr>
<td>
<img src="{{ asset($post->image) }}" alt="">
</td>
<td>
{{ $post->title }}
</td>
<td>
<a href=" {{ route('categories.edit', $post->category->id) }}">
{{ $post->category->name }}
</a>
</td>
when the user post a image, the image will be stored in the linked storage that i've doing before. so here's the code from postscontroller.php if i change the 'posts' to 'post' it says error. because i didn't suitable for the function 'posts' that i write before.
public function store(CreatePostRequest $request)
{
// upload image omegalul
$image = $request->image->store('posts');
// create the post
$post = Post::create([
'title' => $request->title,
'description' => $request->description,
'content' => $request->content,
'image' => $image,
'published_at' => $request->published_at,
'category_id' => $request->category,
'user_id' => auth()->user()->id,
]);
if ($request->tags) {
$post->tags()->attach($request->tags);
}
// flash a message
session()->flash('success', 'Post created successfully');
// redirect the user
return redirect(route('posts.index'));
}
if you guys see any problems that i didn't appeared here, just ask me. Thank you guys so much
If you are working with Laravel Storage it's recommended to use the storage functions to store, get or delete media files.
Use theses commands to do it:
To store:
Storage::disk(config('filesystems.default'))->put($path, $file);
To get:
Storage::disk(config('filesystems.default'))->url($file);
To remove:
Storage::disk('local')->delete($path);
Your code will be like this:
<tbody>
#foreach($posts as $post)
<tr>
<td>
<img src="{{ Storage::disk(config('filesystems.default'))->url($post->image) }}" alt="">
</td>
<td>
{{ $post->title }}
</td>
<td>
<a href=" {{ route('categories.edit', $post->category->id) }}">
{{ $post->category->name }}
</a>
</td>
And:
public function store(CreatePostRequest $request)
{
// upload image omegalul
$image = Storage::disk(config('filesystems.default'))->put('posts', $request->image);
Note: Don't forget to check if your filesystem is setted like 'local' - if you are using local storage.
I am developing project management tool in laravel 5.2. In my application user can create a project and one project has many tasks and one task may have many files attachments. I am using cloudder to save My files. Currently I have assigned My project files to relevant projects only. Now, I need to display the files on each tasks of the relevant projects.
FileController
class FilesController extends Controller
{
public function uploadAttachments(Request $request, $id,$taskId) //this is line 20
{
$this->validate($request, [
'file_name' => 'required|mimes:jpeg,bmp,png,pdf|between:1,7000',
]);
$filename = $request->file('file_name')->getRealPath();
Cloudder::upload($filename, null);
list($width, $height) = getimagesize($filename);
$fileUrl = Cloudder::show(Cloudder::getPublicId(), ["width" => $width, "height" => $height]);
$this->saveUploads($request, $fileUrl, $id,$taskId);
return redirect()->back()->with('info', 'Your Attachment has been uploaded Successfully');
}
private function saveUploads(Request $request, $fileUrl, $id,$taskId)
{
$file = new File;
$file->file_name = $request->file('file_name')->getClientOriginalName();
$file->file_url = $fileUrl;
$file->project_id = $id;
$file->task_id = $taskId;
$file->save();
}
return redirect()->route('projects.show')->with('info', 'File deleted successfully');
}
}
routes
Route::post('projects/{projects}/files', [
'uses' => 'FilesController#uploadAttachments',
'as' => 'projects.files',
'middleware' => ['auth']
]);
and file form is files/form.blade.php
<div class="row" style="border:1px solid #ccc;margin-left:5px;width:100%;padding:15px;">
#foreach($project->files as $file)
<div>
<div><i class="fa fa-check-square-o"></i>
<span>
{{ $file->file_name }}
</span>
</div>
</div>
<hr/>
#endforeach
<form class="form-vertical" role="form"
enctype="multipart/form-data"
method="post"
action="{{ route('projects.files', ['projectId'=> $project->id, 'taskId'=>$task->id])}}">
<div class="form-group{{ $errors->has('file_name') ? ' has-error' : '' }}">
<input type="file" name="file_name" class="form-control" id="file_name">
#if ($errors->has('file_name'))
<span class="help-block">{{ $errors->first('file_name') }}</span>
#endif
</div>
<div class="form-group">
<button type="submit" class="btn btn-info">Add Files</button>
</div>
Now I got this error:
ErrorException in FilesController.php line 20: Missing argument 3 for App\Http\Controllers\FilesController::uploadAttachments()
How can I fix this?
You are not passing the required parameters in your route declaration.
Add projectId and taskId.
Route::post('projects/{projectId}/files/{taskId}', [
'uses' => 'FilesController#uploadAttachments',
'as' => 'projects.files',
'middleware' => ['auth']
]);
And mention them in controller method correctly.
public function uploadAttachments(Request $request, $projectId, $taskId)
{
//
}