Laravel File Uploading - laravel

I have tried the code below for uploading file to laravel but it always go to false (which is noimage.jpg). Links and everything are already linked up through artisan but the image doesnt seem to reach the storage folder. Below are my codes for file handling.
public function store(Request $request)
{
$this->validate($request,[
'title' => 'required',
'body'=>'required',
'cover_image' => 'image|nullable|max:1999'
]);
//Handle File pUpload
if($request->hasFile('cover_image'))
{
//Get Filename with the Extension
$filenameWithExt = $request->file('cover_image')->getClientOriginalName();
//Get Just File Name
$fileName = pathinfo($filenameWithExt,PATHINFO_FILENAME);
//Get Just Extension
$extension = $request->file('cover_image')->getClientOriginalExtension();
//Filename to Store
$fileNameToStore = $fileName.'_'.time().'.'.$extension;
//upload of Image
$path = $request->file('cover_image')->storeAs('public/cover_image',$fileNameToStore);
} else {
$fileNameToStore = 'noimage.jpg';
}
//Create Post
$post = new Post;
$post->title = $request->input('title');
$post->body = $request->input('body');
$post->user_id = auth()->user()->id;
$post->cover_image = $fileNameToStore;
$post->save();
return redirect('/posts')->with('success','Post Created');
}
on the Other hand,below is the code for the "Create Post".
#extends('layouts.app')
#section('content')
<h1>Create Post</h1>
{!! Form::open(['action' => 'PostsController#store', 'POST','enctype' => 'multipart/form-data']) !!}
<div class="form-group">
{{Form::label('title','Title')}}
{{Form::text('title', '', ['class' => 'form-control', 'placegholder' => 'Title'])}}
</div>
<div class="form-group">
{{Form::label('body','Body')}}
{{Form::textarea('body', '', ['class' => 'form-control', 'placegholder' => 'body'])}}
</div>
<div class="form-group">
{{Form::file('cover-image')}}
</div>
{{Form::submit('Submit', ['class'=>'btn btn-primary'])}}
{!! Form::close() !!}
#endsection
but the result in the database is this.
Does anyone have any idea where I went wrong? Thank you so much.

I can share you my library on uploading files
$file = $request->file('YOUR_FILE');
$ext = $file->getClientOriginalExtension()?: "txt";
$mime_type = $file->getMimeType()?:"plain/text";
$path_directory = "new_folder";
if (!File::exists(public_path($path_directory))){
File::makeDirectory(public_path($path_directory), $mode = 0755, true, true);
}
$filename = Helper::create_filename($ext); //create_filename - Str:::random(6) or anything you want
$new_image_filename = $filename;
$file->move($path_directory, $filename);

Related

Add date into table which is in relation with product in Laravel 6

I have product and auction table. I want to add auction deadline on a specific table using form. when I submit the form the product_id in auction table is not populated and deadline shows time on which form is submited.
Here what I am trying:
I want that the create form get the deadline and store in auction table with product id so I can access it in show method of product.
create.blade.php
#extends('layouts.app')
#section('content')
<div class="mt-3" style="margin-left: 50px;">
<h2>Add new product</h2>
{!! Form::open(['action' => 'ProductsController#store', 'method' => 'POST', 'enctype' =>
'multipart/form-data', 'class' => 'w-50 py-3']) !!}
<div class="form-group">
{{Form::label('name', 'Product Name')}}
{{Form::text('name', '', ['class' => 'form-control', 'placeholder' => 'Product Name'])}}
</div>
<div class="form-group">
{{Form::label('description', 'Product Description')}}
{{Form::textarea('description', '', ['class' => 'form-control', 'placeholder' => 'Product Description', 'rows' => '4'])}}
</div>
<div class="form-group">
{!! Form::Label('category', 'Category') !!}
<select class="form-control" name="category_id">
#foreach($categories as $category)
<option value="{{$category->id}}">{{$category->name}}</option>
#endforeach
</select>
</div>
<div class="form-group">
{{Form::label('price', 'Product Price')}}
{{Form::number('price', '', ['class' => 'form-control', 'placeholder' => 'Product Price'])}}
</div>
<div class="form-group">
{{Form::label('deadline', 'Auction Deadline')}}
{{Form::date('{{$auction->deadline}}', '', ['class' => 'form-control'])}}
</div>
<div class="form-group">
{{Form::label('image', 'Product Image')}}
{{Form::file('image', ['class' => '', 'placeholder' => 'Product Image'])}}
</div>
{{Form::submit('Upload Product', ['class' => 'btn btn-primary'])}}
{!! Form::close() !!}
</div>
#endsection
Product Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $fillable = [
'name', 'price', 'description', 'image',
];
public function category()
{
return $this->belongsTo('App\Category');
}
public function auction()
{
return $this->hasOne('App\Auction');
}
}
ProductsController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Product;
use App\Category;
use App\Auction;
class ProductsController extends Controller
{
public function index()
{
$categories = Category::all();
$products = Product::with('category')->latest()->paginate(3);
return view('products.index' ,compact('categories', 'products'));
}
public function create()
{
$categories = Category::all(['id', 'name']);
return view('products.create', compact('categories',$categories));
}
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'description' => 'required',
'category_id' => 'required',
'price' => 'required',
'image' => 'image|nullable',
]);
// Create Product
$product = new Product();
$product->name = request('name');
$product->description = request('description');
$product->category_id = request('category_id');
$product->price = request('price');
$product->image = $fileNameToStore;
$product->save();
$auction = new Auction();
$auction->deadline = request('deadline');
$auction->save();
return redirect('/products')->with('success', 'Product Created');
}
public function show($id)
{
$product = Product::find($id);
return view('products.show', compact('product'));
}
}
you are just creating auction, where is the relation? Delete $product->save(); line. After the $auction->save(); add this line:
$product->auction()->associate($auction);
$product->save();
Final Store method
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'description' => 'required',
'category_id' => 'required',
'price' => 'required',
'image' => 'image|nullable',
]);
// Create Product
$product = new Product();
$product->name = request('name');
$product->description = request('description');
$product->category_id = request('category_id');
$product->price = request('price');
$product->image = $fileNameToStore;
$auction = new Auction();
$auction->deadline = request('deadline');
$auction->save();
$product->auction()->associate($auction);
$product->save();
return redirect('/products')->with('success', 'Product Created');
}
Update for Irrelevant Blade problem
This line is wrong:
{{Form::date('{{$auction->deadline}}', '', ['class' => 'form-control'])}}
You are using blade close string tag in blade string tag.
Should be:
{{Form::date('deadline', '', ['class' => 'form-control'])}}
If auction variable has been passing from controller this will work

How to upload files Laravel 5.5

how to add files to Laravel Storage and save name to DB
i can add one by one but multiple files. i' stuck please help me
This is my View.blade.php
<div class="form-group">
{!! Form::label('name', 'Файлаа энд хуулна уу') !!}
{!! Form::file('attachments[]', ['roles' => 'form', 'multiple' => 'multiple']) !!}
{!! Form::token() !!}
</div>
{!! Form::submit('Submit', ['class' => 'btn btn-success']) !!}
{!! Form::close() !!}
This is my Controller
public function handleUpload(Request $request)
{
if (Auth::check()){
$files = $request->file('attachments');
$allowedFileTypes = config('app.allowedFileTypes');
$maxFileSize = config('app.maxFileSize');
$rules = ['file' => 'required|mimes:'.$allowedFileTypes.'|max:'.$maxFileSize];
$this->validate($request,$rules);
$fileName = now()->format('Y-m-d-H-i-s');
$userName = Auth::user()->name;
$division = $request->input('division');
$destinationPath = config('app.filesDestinationPath').'/'.$division.'/'.$userName.'/'.$fileName;
foreach ($files as $file) {
$uploaded = Storage::put($destinationPath,file_get_contents($file->getRealPath()));
}
if($uploaded){
Project::create([
'description' => $request->input('description'),
'division' => $request->input('division'),
'who' => $request->input('who'),
'whom' => $request->input('whom'),
'content' => $request->input('content'),
'filename' => $division.'/'.$userName.'/'.$fileName
]);
}
return redirect()->to('/projects/');
}
}
You are validating wrong input parameter.
$rules = ['file' => 'required|mimes:'.$allowedFileTypes.'|max:'.$maxFileSize];
Change to -
$rules = ['attachments.*' => 'required|mimes:'.$allowedFileTypes.'|max:'.$maxFileSize];
I have make a whole change according to your code. Try this-
$files = $request->file('attachments');
$allowedFileTypes = config('app.allowedFileTypes');
$maxFileSize = config('app.maxFileSize');
$rules = ['attachments.*' => 'required|mimes:'.$allowedFileTypes.'|max:'.$maxFileSize];
$this->validate($request,$rules);
$userName = Auth::user()->name;
$division = $request->input('division');
$destinationPath = config('app.filesDestinationPath').'/'.$division.'/'.$userName.'/';
foreach ($files as $file) {
$fileName = now()->format('Y-m-d-H-i-s');
$uploaded = Storage::put($destinationPath.$fileName.'.'.$file->getClientOriginalExtension(),file_get_contents($file->getRealPath()));
}

Show popup after confirm form with upload information in Laravel

i have a web page in laravel 5.2, with a form where you must enter a video file to upload to my server.
This is the form:
#extends('layouts.app')
#section('content')
<link href='assets/vendor/parsleyjs/src/parsley.css' rel='stylesheet' />
#if (Auth::guest())
<script type="text/javascript">
window.location = "/";//here double curly bracket
</script>
#else
#if ((Auth::user()->tipo != "profesor") && (Auth::user()->tipo != "alumno"))
<script type="text/javascript">
window.location = "/";//here double curly bracket
</script>
#endif
#endif
<H3 style="margin-top: 0">Subir Video</H3>
{!! Form::open(['id' => 'newVideo', 'route' =>'upload.store', 'method'=>'POST', 'files'=> true, 'data-parsley-validate'=>'' ]) !!}
<div class = "form-group" style ="display: none;">
{!! Form::label('usuario_id', 'usuario_id:') !!}
{!! Form::text('usuario_id', Auth::user()->id) !!}
</div>
<div class = "form-group" style ="display: none;">
{!! Form::label('state', 'State:') !!}
#if (Auth::user()->tipo == "alumno")
{!! Form::text('state', 3) !!}
#else
{!! Form::text('state', 1) !!}
#endif
</div>
{!! Form::label('name', 'Nombre * :') !!}
{!! Form::text('name', null, ['class'=> 'form-control', 'required'=> '']) !!}
{!! Form::label('description', 'Descripción * :') !!}
{!! Form::textarea('description', null, ['class'=> 'form-control', 'required'=> '']) !!}
{!! Form::label('language', 'Idioma * :') !!}
{!! Form::select('language', Config::get('enums.languages'), ['required'=> '', 'data-parsley-mincheck'=> 1]) !!}
<div class = "form-group">
{!! Form::label('imageRef', 'Imagen Referencial de Video * :') !!}
{!! Form::file('imageRef', ['required'=> '']) !!}
</div>
<div class = "form-group">
{!! Form::label('url', 'Video * :') !!}
{!! Form::file('url', ['required'=> '']) !!}
</div>
<div class = "form-group">
{!! Form::label('subtitle', 'Subtitulos:') !!}
{!! Form::file('subtitle') !!}
</div>
<div class = "form-group">
{!! Form::label('trailer', 'Trailer * :') !!}
{!! Form::file('trailer', ['required'=> '']) !!}
</div>
{!! Form::submit('Registrar',['class' =>'btn btn-primary', 'value' =>'validate']) !!}
{!! Form::close() !!}
#endsection
The Route:
Route::resource('upload','MovieController');
The Controller function (MovieController):
public function store(Request $request)
{
/*$validator = Validator::make($request->all(), [$this->validationRules]);
if ($validator->fails()){
return redirect()->back()->withErrors($validator->errors());
}*/
$movie = Movie::create([
'usuario_id' => $request['usuario_id'],
'asignatura_id' => $request['asignatura_id'],
'name' => $request['name'],
'visit' => $request['visit'],
'language' => $request['language'],
'creation_date' => $request['creation_date'],
'description' => $request['description'],
'imageRef' => $request['imageRef'],
'url' => $request['url'],
'state' => $request['state'],
'production_year' => $request['production_year'],
'category' => $request['category'],
'category2' => $request['category2'],
'shooting_format' => $request['shooting_format'],
'direction' => $request['direction'],
'direction_assistant' => $request['direction_assistant'],
'casting' => $request['casting'],
'continuista' => $request['continuista'],
'script' => $request['script'],
'production' => $request['production'],
'production_assistant' => $request['production_assistant'],
'photografic_direction' => $request['photografic_direction'],
'camara' => $request['camara'],
'camara_assistant' => $request['camara_assistant'],
'art_direction' => $request['art_direction'],
'mounting' => $request['mounting'],
'image_postproduction' => $request['image_postproduction'],
'sound_postproduction' => $request['sound_postproduction'],
'catering' => $request['catering'],
'music' => $request['music'],
'actors' => $request['actors'],
]);
$movieId = $movie->id;
if($request['subtitle'] != null){
$sub = Subtitle::create([
'video_id' => $movieId,
'url' => $request['subtitle'],
]);
}
if($request['trailer'] != null){
$trailer = Trailer::create([
'video_id' => $movieId,
'url' => $request['trailer'],
]);
if($request['trailer_subtitle'] != null){
$trailerId = $trailer->id;
$subTrailer = Subtitle::create([
'trailer_id' => $trailerId,
'url' => $request['trailer_subtitle'],
]);
}
}
return "OK";
}
The Model:
class Movie extends Model
{
protected $table = "movies";
protected $fillable = ['usuario_id','asignatura_id','name','language','creation_date','description','imageRef','url','state','production_year','category','category2','shooting_format','direction','direction_assistant','casting','continuista','script','production','production_assistant','photografic_direction','camara','camara_assistant','art_direction','sonorous_register','mounting','image_postproduction','sound_postproduction','catering','music','actors'];
public function setImageRefAttribute($imageRef){
$this->attributes['imageRef'] = Carbon::now()->second.$imageRef->getClientOriginalName();
$name = Carbon::now()->second.$imageRef->getClientOriginalName();
\Storage::disk('local')->put($name, \File::get($imageRef));
}
public function setUrlAttribute($url){
$this->attributes['url'] = 'old/'.Carbon::now()->second.$url->getClientOriginalName();
$name = Carbon::now()->second.$url->getClientOriginalName();
\Storage::disk('local')->put($name, \File::get($url));
$file = pathinfo($name,PATHINFO_FILENAME);
$extension = pathinfo($name,PATHINFO_EXTENSION);
$ffmpeg = \FFMpeg\FFMpeg::create([
'ffmpeg.binaries' => '/Applications/MAMP/htdocs/FFmpeg/ffmpeg',
'ffprobe.binaries' => '/Applications/MAMP/htdocs/FFmpeg/ffprobe',
'timeout' => 0, // The timeout for the underlying process
'ffmpeg.threads' => 12, // The number of threads that FFMpeg should use
]);
$video = $ffmpeg->open($url);
//$format = new CustomVideo();
$format = new FFMpeg\Format\Video\X264('libmp3lame', 'libx264');
$format->on('progress', function ($video, $format, $percentage) {
echo "$percentage % transcoded";
});
$format
-> setKiloBitrate(1000)
-> setAudioChannels(2)
-> setAudioKiloBitrate(256);
$video
->save($format, 'files/convert/videos/'.$file.'.mp4');
$this->attributes['url'] = $file.'.mp4';
$ffmpeg_path = '/Applications/MAMP/htdocs/FFmpeg/ffmpeg'; //Path to your FFMPEG
$video_path = 'files/convert/videos/'.$file.'.mp4'; // Path to your Video
$command = $ffmpeg_path . ' -i "' . $video_path . '" -vstats 2>&1';
$output = shell_exec($command);
$regex_duration = "/Duration: ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}).([0-9]{1,2})/";
$hours = 0;
if (preg_match($regex_duration, $output, $regs)) {
$hours = $regs [1] ? $regs [1] : null;
$mins = $regs [2] ? $regs [2] : null;
$secs = $regs [3] ? $regs [3] : null;
$video_Length = $hours . ":" . $mins . ":" . $secs;
$this->attributes['duration'] = $video_Length;
}
/*->save(new FFMpeg\Format\Video\X264(), 'export-x264.mp4')
->save(new FFMpeg\Format\Video\WMV(), 'export-wmv.wmv')
->save(new FFMpeg\Format\Video\WebM(), 'export-webm.webm');*/
//audio
/* $ffmpeg = FFMpeg\FFMpeg::create();
$audio = $ffmpeg->open('track.mp3');
$format = new FFMpeg\Format\Audio\Flac();
$format->on('progress', function ($audio, $format, $percentage) {
echo "$percentage % transcoded";
});
$format
-> setAudioChannels(2)
-> setAudioKiloBitrate(256);
$audio->save($format, 'track.flac');*/
}
public static function Movies(){
return DB::table('movies')
->join('subjects','subjects.id','=','movies.asignatura_id')
->select('movies.*')
->get();
}
}
I need display a popup when the form is submitted with information of the video upload similar to xibo popup but much simpler.
I need something like this:
I failed to find the solution.

Video uploading not working in laravel 5

I am working on uploading the videos for my website. But i unable to do it. I have search many documents but i am fail to solve it. Can any one help me out to solve this problem?
I am getting an error "Call to a member function getClientOriginalName() on null"
//Form code for video upload..
{!! Form::open(array('url' => 'video' , 'files' => true)) !!}
<div class="form-group">
{!! Form::label('video_name', 'Video Name : ') !!}
{!! Form::text('name',null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('video_path', 'Select Video : ') !!}
{!! Form::file('path', ['class' => 'form-control'])!!}
</div>
<div class="form-group">
{!! Form::submit('Upload Video') !!}
</div>
{!! Form::close() !!}
//Controller Code
public function store(Request $request){
$data = $request->all();
if ( $request->hasFile( 'path' ) ) {
$file = $request->file( 'path' );
$name = $file->getClientOriginalName();
$data[ 'path' ] = $name;
$destination = '/public/videos';
$request->file( 'path' )->move( base_path() . $destination, $name );
return $name;
}
else {
return '<script>alert("Fail")</script>';
}
}
//The above code is working for images, doucments and audio but not working for videos.
Thanks in advance
If your uploaded video is larger than the upload setting in your php.ini then you get this problem.
I suggest check your php.ini file and increase these directives as needed
php.ini
Example
post_max_size=200M
upload_max_filesize=200M

Laravel 4: Route::post return URL with model name in brackets instead of id

I am building a post/comment system, with the comment form inside the post view. So, when I'm watching a post in the url http://example.dev/post/1 and click on the form submit buttom the url goes to http://example.dev/post/%7Bpost%7D where %7B = { and %7D = }).
I think the controller associated to the url post method doesn't even start.
My routes:
Route::model('post','Post');
Route::get('partido/{post}', 'FrontendController#viewPost');
Route::post('partido/{post}', array(
'before' => 'basicAuth',
'uses' => 'FrontendController#handleComment'
)
);
My viewPost controller:
public function viewPost(Post $post)
{
$comments = $post->comments()->get();
return View::make('post')
->with(compact('comments'))
->with(compact('posts'));
}
My handleComment controller:
public function handleComment(Post $post)
{
// Get the data
$data = Input::all();
// Build the rules
$rules = array(
'title' => 'required',
'description' => 'required',
);
// Error messages
$messages = array(
'title.required' => 'Title required.',
'description.required' => 'Description required.',
);
// Validator: He Comes, He sees, He decides
$validator = Validator::make($data, $rules, $messages);
if ($validator->passes()) {
// Save the new comment.
$comment = new Comment;
$comment->title = Input::get('title');
$comment->description = Input::get('description');
$post->comments()->save($comment);
return Redirect::to('post/'.$post->id.'');
}
else {
return Redirect::to('post/'.$post->id.'')->withErrors($validator);
}
}
And the form in the view:
{{ Form::open(array(
'action' => 'FrontendController#handleComment', $post->id
)) }}
<ul class="errors">
#foreach($errors->all() as $message)
<li>{{ $message }}</li>
#endforeach
</ul>
{{ Form::label('title', 'Title')}}<br />
{{ Form::text('title', '', array('id' => 'title')) }}
<br />
{{ Form::label('description', 'Description')}}<br />
{{ Form::textarea('description', '', array('id' => 'description')) }}
<br />
{{ Form::submit('Submit') }}
{{ Form::close() }}
You need another array for the Form::open() - try this:
{{ Form::open(array('action' => array('FrontendController#handleComment', $post->id))) }}

Resources