I can successfully upload my video with the below code. But when i display the video in the view page it's blank.
public function store(Request $request)
{
if(Auth::check())
{
if(Input::hasFile('video'))
{
$file = $request->file('video');
$videomimes = ['video/mp4'];
if (in_array($file->getMimeType() ,$videomimes)) {
$filevalidate = 'required|mimes:mp4';
}
$this->validate($request, [
'video' => $filevalidate,
]);
$filename = 'Tag '.$request->input('tag_no').'.'.$file->getClientOriginalExtension();
$request->death_video->move(public_path('/storage/videos'), $filename);
$stock = Stock::create([
'tag_no' => $request->input('tag_no'),
'video'=> $filename,
'user_id' => Auth::user()->id
]);
if($stock){
return redirect()->route('stocks.index')
->with('success' , 'Stock created successfully');
}
}
}
return back()->withInput()->with('errors', 'Error creating new Stock');
}
This is my schema:
Schema::create('stocks', function (Blueprint $table) {
$table->increments('tag_no');
$table->binary('video');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
This is how i display video:
<video width="320" height="240" controls>
<source src="/storage/videos/{{$stock->video}}" type="video/mp4">
Your browser does not support the video tag.
</video>
I can hear the audio but no visual is shown! How to solve this?
If you are store video in public directory then try use URL helper
<source src="{{url('/storage/videos/'.$stock->video)}}" type="video/mp4">
Related
Hi I am making a Private chat Application In Livewire but the Thing is When i Insert a message don't show Unless I reload the Page please help me how can i resolved that ? thank u.
I am using Livewire Full-Page Components here is the Code
Note :- I am using this render function inside viewMessage function but data is not updated without page relaod.
this will load the all the conservation message
$this->render();
app\Http\Livewire\Messaging.php
class Messaging extends Component
{
public $body;
public $searchTerm;
public $selectedUser;
public function mount(){
$this->selectedUser =User::where('id','!=',Auth::user()->id)
->first();
}
public function render()
{
$searchTerm = '%'.$this->searchTerm.'%';
if($searchTerm){
$user= User::where('id', '!=', Auth::user()->id)
->where('user_type',1)
->where('email', 'like', $searchTerm)
->with('messages')
->get();
}
$conservation = Message::query()
->where('sender_id', Auth::user()->id)
->where('receiver_id', $this->selectedUser->id)
->orWhere('receiver_id', Auth::user()->id)
->where('sender_id', $this->selectedUser->id)
->with('sender')
->with('receiver')
->get();
return view('livewire.messaging',[
'users' => $user,
'conservation' =>$conservation
]);
}
public function viewMessages($userId){
$this->selectedUser = User::findorFail($userId);
$senderExist = Message::where('sender_id',$this->selectedUser->id)->exists();
if($senderExist){
$message = Message::where('sender_id',$this->selectedUser->id)->orderBy('receiver_id','Desc')->get();
foreach($message as $value){
$value->notification = "0";
$value->save();
}
}
}
public function sendMessages(){
Message::create([
'receiver_id' => $this->selectedUser->id,
'sender_id' => Auth::user()->id,
'body' => $this->body,
]);
$this->reset('body');
$this->viewMessages($this->selectedUser->id);
$this->render(); //this will load the all the conservation message
}
}
resources\views\livewire\messaging.blade.php
<form wire:submit.prevent="sendMessages" action="#" >
<div class="position-absolute bottom-0 col-md-12 pe-3">
<div class="input-group comment-box p-3">
<input wire:model.defer="body" type="text" class="form-control"
placeholder="Type Message ..." aria-label="Aa" aria-describedby="button-addon2" required>
<button class="btn btn-outline-secondary py-0 px-3" type="submit" id="button-addon2"><i class='bx bx-send fs-4'></i></button>
</div>
</div>
</form>
I personally would not suggest loading in data on every single render. Livewire is able to hydrate previously fetched models and collections, which takes away the strain of reloading it from your database each render. I personally would write your component as such:
use Illuminate\Support\Collection;
class Messaging extends Component
{
public $body = '';
public $searchTerm = '';
public $selectedUser;
// Assuming you're using PHP 7.4 or above, else remove typehint
public Collection $users;
public Collection $conversation;
// Ensure we validate the data passed
protected $rules = [
'body' => ['required', 'string'],
];
public function mount()
{
$this->selectedUser = User::where('id','!=',Auth::user()->id)->first();
$this->getUsers();
$this->getConversation();
}
public function render()
{
return view('livewire.messaging');
}
public function updated($field)
{
// Only update the users if the search term has changed
if ($field === 'searchTerm') {
$this->getUsers():
}
}
public function viewMessages($userId)
{
$this->selectedUser = User::findorFail($userId);
$senderExist = Message::where('sender_id',$this->selectedUser->id)->exists();
if($senderExist) {
$messages = Message::where('sender_id',$this->selectedUser->id)->orderBy('receiver_id','desc')->get();
foreach($messages as $message){
$message->notification = "0";
$message->save();
}
// Are you saving the messages one by one to trigger model events? If not, use below query to instantly update all of them at once in the database:
// Message::where('sender_id',$this->selectedUser->id)->orderBy('receiver_id','desc')->update([
// 'notification' => 0,
// ]);
}
}
public function sendMessages()
{
// Validate the data as per given rules
$this->validate();
Message::create([
'receiver_id' => $this->selectedUser->id,
'sender_id' => Auth::user()->id,
'body' => $this->body,
]);
$this->reset('body');
$this->viewMessages($this->selectedUser->id);
// Refresh conversation
$this->getConversation();
}
public function getConversation()
{
$this->converstaion = Message::query()
->where('sender_id', Auth::user()->id)
->where('receiver_id', $this->selectedUser->id)
->orWhere('receiver_id', Auth::user()->id)
->where('sender_id', $this->selectedUser->id)
->with('sender')
->with('receiver')
->get();
}
public function getUsers()
{
$query = User::where('id', '!=', Auth::user()->id)
->where('user_type', 1)
->with('messages');
if (! empty($this->searchTerm)) {
$searchTerm = '%'.$this->searchTerm.'%';
$query->where('email', 'like', $searchTerm);
}
$this->users = $query->get();
}
}
The render method gets called by Livewire itself each time something happens, such as a value change of a variable, or after a function was called. You should not call it yourself.
P.S. For Livewire to fully keep track of what is what, I suggest adding wire:key to data rows. For example, on a div that is holding the data to your conversation messages, add wire:key="message-{{$message->id}}". This way, if a data change happens, Livewire knows exactly what date should be changed. Read more about it here
You should use the livewire emite event
https://laravel-livewire.com/docs/2.x/events
Am working on an app that should upload multiple images in the database using laravel and vue js.
Now for some reason it keeps on returning null value on the back end side. Hope someone can pin point the problem in this code.
this is my front-end code vue js
<template>
<div>
<div>
<form #submit.prevent="submit">
<input type="file" #change="onChange" multiple/>
<input type="submit" value="Upload">
</form>
</div>
</div>
</template>
<script>
export default {
data: ()=>({
image:[],
}),
methods:{
onChange(e){
this.image = e.target.files[0];
},
submit(){
let payload = new FormData();
for(let i=0; i<this.image.length; i++){
payload.append('image[]', this.image[i])
}
axios.post('/api/formsubmit',payload).then(res=>{
console.log("Response", res.data)
}).catch(err=>console.log(err))
}
},
}
</script>
and this is may back-end code Laravel 7
public function multipleupload(Request $request)
{
try{
if($request->hasFile('image')){
$upload = $request->file('image');
$file_name = time().'.'.$upload->getClientOriginalName();
$upload->move(public_path('image'), $file_name);
return response()->json([
'message'=>'File upload successfully!'
], 200);
}else {
return 'no data';
}
}catch(\Exception $e){
return response()->json([
'message'=>$e->getMessage()
]);
}
}
This code will always return 'no data'. been trying to figure it out but with no progress I hope someone can help.
Thanks,
if you want to upload multiple images you have to do loop, you can try this :
public function multipleupload(Request $request)
{
$input = $request->all();
request()->validate([
'image' => 'required',
]);
if($request->hasfile('image'))
{
foreach($request->file('image') as $image)
{
$imageName=file_name =$image->getClientOriginalName();
$image->move(public_path().'/images/', $imageName);
$insert['image'] = "$imageName";
}
}
Image::create($insert);
return back()
->with('success','Multiple Image Upload Successfully');
}
I am getting this issue, and I don't understand what I am doing wrong as I did this same exact approach for another component on this site, and works perfectly....
ViewMessages.php
public $messages;
public function mount($messages)
{
$this->messages = $messages;
}
view-messages.blade.php
<div class="flex flex-col">
#foreach ($messages as $message)
{{$message->content}}
#endforeach
</div>
Everything works and it outputs all the messages correctly.
When I try and pass in a livewire component into the for each, it gives that error.
#foreach ($messages as $message)
#livewire('chat.show-message', ['message'=>$message], key('show-message-'.$message->id))
#endforeach
// ShowMessage.php
public $user;
public $message;
public $user_id;
public $content;
public function mount($message)
{
$this->message = $message;
}
Honestly am lost on what I am doing wrong, as I copied the exact same code and changed the variables that I used before. It works right now on the site when I do nested components.
<div class="flex flex-col space-y-4 py-4 overflow-y-auto">
#foreach ($chats as $chat)
#livewire('kanbans.show-sidebar-chat-message', ['chat'=>$chat], key('chat-'.$chat->id))
#endforeach
</div>
I redid this component already twice, and can't find any syntax issues or spelling errors. =/
The issue was with the DB Facade query
$messages = DB::select('SELECT * FROM chat_messages
WHERE (receiver_id = :auth_id and user_id = :user) OR (receiver_id = :user2 AND user_id = :auth_id2)',
['auth_id' => $auth_id, 'user' => $user->id, 'auth_id2' => $auth_id, 'user2' => $user->id]);
Although not sure yet how to pass in the $user->id but when I set the user id to #2, the livewire components work as intended.
public function view($user)
{
$user=User::where('id',$user)->firstOrFail();
$messages = ChatMessage::where(function ($query){
$query->where('user_id', '=', auth()->id() )
->where('receiver_id', '=', 2 );
})->orWhere(function ($query){
$query->where('user_id', '=', 2)
->where('receiver_id', '=', auth()->id() );
})->get();
return view('backend.chat.view-contact-chat',compact('user','messages'));
}
I have a Laravel program that saves form data and uploads a few pictures. In the validation, there are two rules. The image is required and it has to be of image type (jpg, jpeg, png). However, the validation only checks for the filetype and does not check for 'required'. Even if there is no image, it allows the user to submit. Why?
public function updateImages(Request $request, $id)
{
$validatedData = $request->validate([
'image' => 'required',
'image.*' => 'image|mimes:jpeg,png,jpg|max:2048',
],
[
'image.*.image' => 'Format Error: Please uplaod image in a png or jpg format',
]);
$item = Post::find($id);
$existing_count = Photo::where('post', $item->id)->count();
$countrequest = sizeof($request->file('image'));
$count = $existing_count + $countrequest;
if ($count >= 6) {
return back()
->withInput()
->withErrors(['Only 5 images can be uploaded!']);
}
$upload = $this->imageUpload($item, $request);
return redirect()->back()->with('message', 'Image Updated');
}
Apply require with image.*. Eg.-
image.*' => 'require|image|mimes:jpeg,png,jpg|max:2048',
Try this solution. It will work.
You can use Laravel Request Validation
To create a form request class
php artisan make:request ImageUpdateRequest
Go to app/Http/Requests add the rules
public function authorize()
{
return true;
}
public function rules()
{
return [
'image' => 'required|image|mimes:jpeg,png,jpg|max:2048'
];
}
On your controller
use App\Http\Request\ImageUpdateRequest;
public function updateImages(ImageUpdateRequest $request, $id)
{
$item = Post::find($id);
$existing_count = Photo::where('post',$item->id)->count();
$countrequest = sizeof($request->file('image'));
$count= $existing_count+$countrequest;
if ($count >= 6 ){
return back()
->withInput()
->withErrors(['Only 5 images can be uploaded!']);
}
$upload = $this->imageUpload($item, $request);
return redirect()->back()->with('message', 'Image Updated');
}
Hello i have a form for image upload
<input type="file" name="ad_image[]">
i want only one image to be required and others to be optional.
This is my validation rule and is not working:
'ad_image.*' => 'required|min:1|mimes:png,gif,jpeg,jpg|max:300',
i have tryed this:
'ad_image' => 'required|array|min:1|mimes:png,gif,jpeg,jpg|max:300',
also not working, when i upload jpg file there is error "The ad image must be a file of type: png, gif, jpeg, jpg."
please help with this issue
You can try:
public function rules()
{
$rules = [
'ad_image0'=> 'image|required|mimes:png,gif,jpeg,jpg|max:300'
];
$nbr = count($this->input('ad_image')) - 1;
foreach(range(0, $nbr) as $index) {
$rules['ad_image.' . $index] ='image|mimes:png,gif,jpeg,jpg|max:300';
}
return $rules;
}
I have decided to make my own custom validation rule:
This code is in boot method of the AppServiceProvider
public function boot()
{
Validator::extend('require_one_of_array', function($attribute, $value, $parameters, $validator) {
if(!is_array($value)){
return false;
}
foreach ($value as $k => $v){
if(!empty($v)){
return true;
}
}
return false;
});
}
The validation message is manualy added as third parameter of the validator
$messages = [
'require_one_of_array' => 'You need to upload at least one pic.',
];
And this is how is used to make sure at lease one image is uploaded (this is in rules array):
'ad_image' => 'require_one_of_array',
'ad_image.*' => 'mimes:jpeg,bmp,png|max:300',