Laravel 9 Livewire The photo failed to upload - laravel

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

Related

Laravel Livewire Pagination Result Disappear After Clicking Next Page/Page Number

i've been searching for a question like the one above but i can't find one, so i'm gonna make one
My problem is, when i make a very simple pagination with Laravel Livewire, the first page appear just fine, but when i click "Next Page/Page Number", the result just disappear, even though there are still more results to show, i'm absolutely got no idea, no mattter how i try.
As you can see, the simple pagination work just fine, there is next and previous button and a very big next and previous picture below
But the moment i click next page or page number, the result just disappear, the total number of result even go to 0
Here is my Component code:
namespace App\Http\Livewire;
use Livewire\Component;
use Illuminate\Http\Request;
use DB;
use Livewire\WithPagination;
class Category extends Component
{
use WithPagination;
public function render(Request $request)
{
$id = $request->id;
$product_count = DB::table('product')->where('category_id', $id)->count();
$page = $request->page ?? 1;
$product_all = DB::table('product')->where('category_id', $id)->paginate(3);
return view('livewire.category',[
'product_all' => $product_all,
'product_count' => $product_count,
'page' => $page,
]);
}
}
Here is my view code:
<div class="row">
#foreach ($product_all as $product)
<div class="col-lg-4 col-md-6 col-12 mt-4 pt-2">
#php
product($product);
#endphp
</div>
#endforeach
<!-- PAGINATION START -->
#if ($product_all instanceof \Illuminate\Pagination\LengthAwarePaginator)
{{ $product_all->links() }}
#endif
<!-- PAGINATION END -->
</div>
And a small notice, i try pagination(just normal laravel pagination) without livewire and it work perfectly fine, that's why i am really clueless of what is happening
I have already include the livewire #livewireStyles and #livewireScripts, and i can't find an answer anywhere else cause i don't see any question that match my problem, and i'm kinda new to livewire
I think your problems is related with the request parameter on the render method of the livewire component, once livewire on rerender can't access the request value, until next browser refresh.
public function render(Request $request)
instead, use livewire properties to bind the id and page with values livewire can read on rerenders
#livewire('some-component', ['category_id' => $parent_category_id, 'page' => $parent_page_value])
Like above, livewire bind this values to self properties and read from them on rerender
public $category_id, $page;
public function render()
{
$product_count = DB::table('product')->where('category_id', $this->category_id)->count();
$product_all = DB::table('product')->where('category_id', $this->category_id)->paginate(3);
return view('livewire.category',[
'product_all' => $product_all,
'product_count' => $product_count,
'page' => $this->page,
]);
}

Trying to get property 'image' of non-object in Laravel

I am working on a laravel project. In this project, when i try to view and edit the profile page. I am getting this error.
ErrorException
Trying to get property 'image' of non-object (View: C:\xampp\htdocs\HomeServices\resources\views\livewire\sprovider\sprovider-profile-component.blade.php)
http://127.0.0.1:8000/sprovider/profile
SproviderProfileComponent.php :-
<?php
namespace App\Http\Livewire\Sprovider;
use App\Models\ServiceProvider;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
class SproviderProfileComponent extends Component
{
public function render()
{
$sprovider = ServiceProvider::where('user_id',Auth::user()->id)->first();
return view('livewire.sprovider.sprovider-profile-component',['sprovider'=>$sprovider])->layout('layouts.base');
}
}
Models/ServiceProvider.php :-
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class ServiceProvider extends Model
{
use HasFactory;
protected $fillable = ['user_id'];
public function category()
{
return $this->belongsTo(ServiceCategory::class,'service_category_id');
}
}
sprovider-profile-component.blade.php
<div class="panel-body">
<div class="row">
<div class="col-md-4">
#if($sprovider->image)
<img src="{{asset('images/sproviders')}}/{{$sprovider->image}}" width="100%" />
#else
<img src="{{asset('images/sproviders/default.jpg')}}" width="100%" />
#endif
</div>
<div class="col-md-8">
<h3>Name: {{Auth::user()->name}}</h3>
<p>{{$sprovider->about}}</p>
<p><b>Email: </b>{{Auth::user()->email}}</p>
<p><b>Phone: </b>{{Auth::user()->phone}}</p>
<p><b>City: </b>{{$sprovider->city}}</p>
<p><b>Service Category: </b>
#if($sprovider->service_category_id)
{{$sprovider->category->name}}
#endif
</p>
<p><b>Service Locations: {{$sprovider->service_locations}}</b></p>
Edit Profile
</div>
</div>
</div>
The only reason this could happen is because $sprovider is null.
When it happens, $sprovider->image will translate to (null)->image, which is indeed Trying to get property 'image' of non-object.
You could do this to prevent $sprovider from being null:
$sprovider = ServiceProvider::where('user_id',Auth::user()->id)->firstOrFail();
By using firstOrFail instead of first, you ensure $sprovider will never be null (like the name suggests, if it doesn't find any provider, it will fail).
You will have another error saying that no provider could be found, this is another issue, probably because you don't have any provider for this user or something like that.
Two possibilities
$sprovider is null and
image key is not available in $sprovider ($sprovider->image) may be you mis-spelled image in database table so for that just use dd($sprovider); or print_r($sprovider); and check image key is available or not.

How to destroy a record using a form in Laravel and display status?

I'm using Laravel and I am currently implementing the 'destroy' method in a resource controller as part of CRUD. The method should delete the specified record in my database.
The method is called by my blade.php file, which uses a form with the DELETE method and route('my-resources.destroy', $my-resource->id). I want the controller to return a string such as 'Deleted successfully!' so that I can display that to the client.
Here is my code:
In views/book/edit.blade.php:
<form method="DELETE" action="{{ route('books.destroy', $book->id) }}">
<div class="form-item center">
<button type="submit" class="btn-danger">Delete</button>
</div>
</form>
and in BookController.php:
public function destroy($id)
{
$book = Book::find($id);
$book->delete();
return redirect()->away('https://www.google.com');
}
I put a redirect to google.com just to see if the redirect works, but it doesn't. When I click the 'Delete' button, the url changes from http://127.0.0.1:8000/books/1/edit to http://127.0.0.1:8000/books/1? with that question mark at the end. What am I doing wrong?
I have another question: if I want to return the status, should I use something like
Route::get('/', function () {
return 'Deleted successfully';
});
or
$request->session()->flash('status', 'Task was successful!');
/** and some random return statement **/
Thanks!
Forms do not support the DELETE method so you need to use the Laravel #method helper to tell Laravel you want to use the DELETE verb. Additionally, you need to include the csrf token that Laravel expects are part of preventing cross-site request forgeries.
<form action="{{ route('books.destroy', $book->id) }}" method="POST">
#csrf
#method("DELETE")
... // Button/link for submit this form
</form>
You may need to define your route so that it accepts a DELETE request, unless you have defined a resourceful route:
Route::delete('/books/{id}', 'BookController#destroy')
->name('books.destroy'); // Laravel 7
Route::delete('/books/{id}', [\App\Http\Controllers\BookController::class, 'destroy'])
->name('books.destroy'); // Laravel 8
If you're using resourceful routes, they will be made available for you already:
Route::resource('/books', 'BookController'); // Laravel 7
Route::resource('/books', \App\Controllers\Http\BookController::class); // Laravel 8
For your destroy method, set a flash message to be sent back:
public function destroy(Book $id)
{
$id->delete();
return redirect('/')->with('success', 'Book deleted');
}
Then flash the message in your view:
#if (session('success'))
<p>{{ session('success') }}</p>
#endif

Laravel does not display uploaded image

I'll need your help there, I have a form when I submit an image, it's working fine, but when I try to display the image on an another page, its display a white square (I can see that it's working because I can see the name of the image in the console).
This is my app.blade.php :
<div class="menu_connect_big_screen">
<img src="{{Auth::user()->image}}"/>
<p>{{Auth::user()->firstName}} {{Auth::user()->lastName}}</p>
Mon compte | Se déconnecter
</div>
And this is my controller :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use Auth;
class ProfilePictureController extends Controller
{
public function update(Request $request)
{
$request = $request->All();
User::where('id', Auth::user()->id)
->update(
[
'image' => $request['image']]
);
return redirect()->to('/')->with(['image-changed' => 'Photo de profil modifiée !']);
}
}
I'm kinda new to laravel so any help would be thankful.
Thank you.
If the image is stored in blob you should use base64 in your image tag like so;
<img src="data:image/jpeg;base64,{{base64_encode( Auth::user()->image )}}"/>
However, this is not specific to Laravel.
For example user images stored in public/user_images directory
<div class="menu_connect_big_screen">
<img src="{{ asset('user_images/' . Auth::user()->image) }}" height="50px" width="50px">
<p>{{Auth::user()->firstName}} {{Auth::user()->lastName}}</p>
Mon compte | Se déconnecter
</div>

I want to upload and save image in database but when i try to do it Call to a member function images() on null error shown up

I am beginner in laravel and i want to make image uploading and saving app.
Everything is going cool but as i try to upload images it isnot saved to database.
But in public/gallery/images folder images are present.How this is possible without saving in database.
When i try to upload following error shown up:
FatalErrorException in GalleryController.php line 71:
Call to a member function images() on null
My controller is:
public function doImageUpload(Request $request){
//get the file from the post request
$file = $request->file('file');
//set my file name
$filename = uniqid() . $file->getClientOriginalName();
//move the file to correct location
$file->move('gallery/images',$filename);
//save image details into the database
$gallery = Gallery::find($request->input('gallery_id'));//get the gallery_id
$image = $gallery->images()->create([
'gallery_id'=>$request->input('gallery_id'),
'file_name'=>$filename,
'file_size'=>$file->getClientSize(),
'file_mime'=>$file->getClientMimeType(),
'file_path'=>'gallery/images/' . $filename,
'created_by'=>1,
]);
My view is:
<div class="row">
<div class="col-md-12">
<form action="{{url('image/do-upload')}}"
method="POST" enctype="multipart/form-data">
<label>Select image to upload:</label >
<input type="file" name="file" id="file">
<input type="submit" value="Upload" name="submit">
<input type="hidden" name="_token" value={{ csrf_token() }}>
</form>
</div>
and my image model is:
class Image extends Model
{
protected $fillable = [
'gallery_id','file_name','file_size','file_mime','file-path','created_by'
];
public function gallery(){
return $this->belongsTo('App\Gallery');
}
}
Being new to laravel i didnt get the actual error meaning Call to a member function images() on null??
How to fix this?
do a log debug on $gallery after you use the find method, there's a good chance it's not initialized, if the find method fails to find the id you've given it, it returns null
a good practice would be to verify you get an object back and verify your input contains gallery_id and that it is a number > 0
if ($request->has('gallery_id') && intval($request->input('gallery_id'))>0){
$gallery = Gallery::find($request->input('gallery_id'));//get the gallery_id
if ($gallery){
$image = $gallery->images()->create([
'gallery_id'=>$request->input('gallery_id'),
'file_name'=>$filename,
'file_size'=>$file->getClientSize(),
'file_mime'=>$file->getClientMimeType(),
'file_path'=>'gallery/images/' . $filename,
'created_by'=>1,
]);
} else {
return Response::make('no gallery found with this $request->input('gallery_id') gallery_id',404);
}
} else {
return Response::make('invalid gallery_id as input',400);
}
you could also create the image via the Image create method as is instead of using the gallery relationship, that would have created an image probably with the gallery_id of 0 if the galley_id input is incorrect.
$image = Image::create([
'gallery_id'=>$request->input('gallery_id'),
'file_name'=>$filename,
'file_size'=>$file->getClientSize(),
'file_mime'=>$file->getClientMimeType(),
'file_path'=>'gallery/images/' . $filename,
'created_by'=>1,
]);
I don't know if you resolved the problem, but I had the same issue and I found the solution.
When you send a form, you need to put a hidden input .
<input type"hidden" name="gallery_id" value="{{ $gallery->id }}">
I'm sure you work on the same project as me, DropZone Gallery, if so I think you have the solution

Resources