post is not showing in browser while saving in databaser :laravel - php

I m working on showing a post, when i post data with the image then my data stored in DB (image is also storing into destination folder) but not showing on the browser, here is the code of the page(index.blade.php) on which m trying to show post:
#extends('layouts.app')
#section('content')
<form method="POST" action="{{url('posts')}}" enctype="multipart/form-data">
<!--#if(session('message'))
{{session('messgae')}}
#endif-->
#if(count($errors) > 0)
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
#endif
{{csrf_field()}}
Name:- <input type="text" name="title" value="{{old('title')}}">
Text:- <textarea name="body">value="{{old('body')}"></textarea>
Upload File:- <input type="file" name="thumbnail" value="{{old('thumbnail')}}">
<input type="submit" value="submit">
</form>
#endsection
this is post controller
public function store(Request $request)
{
if($request->hasFile('thumbnail') && $request->thumbnail->isValid())
{
$extension = $request->thumbnail->extension();
$filename = time()."_.".$extension;
$request->thumbnail->move(public_path('images'), $filename);
}
else
{
$filename = 'code.png';
}
\App\Post::create([
'title' => $request->title,
'body' => $request->body,
'thumbnail' => $filename,
]);
return redirect('posts');
}

I found a mistake in your code
#foreach($posts as post)
use
#foreach($posts as $post)

Related

Get the actual file name and extention from image file in laravel

When I am uploading an image to the form and returning it from the controller, the image name and extention are changing.I am a beggar, so if I make a mistake while asking a question, I would like to apologize.
This is my form:
<form action="{{ route('admin.slider.store') }}" method="POST" enctype="multipart/form-data">
#csrf
<div class="row">
<div class="col-md-12">
<label class="control-label">Image</label>
<input type="file" name="image">
</div>
</div
<button type="submit" class="btn btn-success">Save</button>
</form>
This is my controller:
public function store(Request $request)
{
$this->validate($request, [
'image' => 'required|mimes:jpeg,bmp,png,jpg',
]);
$image = $request->file('image');
return $image;
}
My image file name is :demo.jpg
Controller return result is like that:
C:\xampp\tmp\php5E86.tmp
This is the same result when I give another picture, only the last four characters are changing.
C:\xampp\tmp\phpF239.tmp
It is very helpful to know why I am getting .tmp file return.
use getClientOriginalName to get orginal file name
$request->image->getClientOriginalName()
To get file extension
$request->image->extension();
or
$name = $request->file('image')->getClientOriginalName();
$extension = $request->file('image')->extension();
Ref:https://laravel.com/docs/8.x/filesystem#other-uploaded-file-information

image doesn't display from database Codeigniter 4

i am new using codigniter. i am trying to display images from the mysql database by sending them to the database using a create page where you can type in a title, some info and select an image, everything displays after creating a project except for the image. once i open phpmyadmin it shows that there is data for the image but it looks like it's only MetaData and not the actual image itself. i have been stuck on this for a couple of days now so i hope you guys could help me out!
create function in The Controller (edited):
public function create(){
$model = new ProjectModel();
$file = $this->request->getFile('image');
if ($this->request->getMethod() === 'post' && $this->validate([
'title' => 'required|min_length[3]|max_length[255]',
'info' => 'required',
'image' => 'uploaded[image]',
]))
{
$model->save([
'title' => $this->request->getPost('title'),
'slug' => url_title($this->request->getPost('title'), '-', TRUE),
'info' => $this->request->getPost('info'),
$tempfile = $file->getTempName(),
$imgdata = file_get_contents($tempfile),
]);
var_dump($imgdata);
#echo view('project/success');
}
else
{
echo view('site/create');
}
}
My Model
namespace App\Models;
use CodeIgniter\Model;
class ProjectModel extends Model
{
protected $table = 'projects';
protected $allowedFields = ['title', 'slug', 'info', 'image'];
public function getProjects($slug = false)
{
if ($slug === false)
{
return $this->findAll();
}
return $this->asArray()
->where(['slug' => $slug])
->first();
}
}
this is the file that creates a div element once you press the create button
<?php if (! empty($projects) && is_array($projects)) : ?>
<?php foreach ($projects as $project_item): ?>
<div class="project-box" href="/projects/<?= esc($project_item['slug'], 'url') ?>">
<?php echo '<img class="project-image" src="data:image/jpeg;base64,'.base64_encode($project_item['image']).'" alt="image" ">'?>
<p class="project-name"><?=esc($project_item['title'])?></p>
<div class="bottom-border">
<p class="project-creator"><i class="far fa-user-circle"></i> <?=esc($project_item['creator'])?></p>
<div class="statistics">
<p class="project-likes"><i class="fas fa-heart"></i> <?=esc($project_item['likes'])?></p>
<p class="project-views"><i class="far fa-eye"></i> <?=esc($project_item['views'])?></p>
</div>
</div>
</div>
<?php endforeach; ?>
<?php else : ?>
<h3>No Projects</h3>
<?php endif ?>
this is the create file in which you can create a project
<div class="parent">
<?= \Config\Services::validation()->listErrors() ?>
<form action="/site/create" method="post">
<h1>Create Project</h1>
<?= csrf_field() ?>
<div class="form-group">
<input class="ph-title" type="input" name="title" placeholder="Title" /><br/>
</div>
<div class="grow-wrap">
<textarea class="ph-info" name="info" placeholder="Type in project info"></textarea>
</div>
<!-- <div class="file-input">
<label for="file">
Select file
<p class="file-name"></p>
</label>
</div> -->
<input class="file-btn" type="file" name="image" value=""/><br/>
<input class="create-btn" type="submit" name="submit" value="Create Project"/>
</form>
</div>
What am i doing wrong?
There are a few things wrong here. First off, your form is set for image uploading, but needs the enctype added to the form tag so that your backend PHP can recieve the $_FILES object
<form action="/site/create" method="post" enctype="multipart/form-data">
Remove the value="" from the input...
<input class="file-btn" type="file" name="image" />
Now you're ready to receive a file - see https://codeigniter4.github.io/userguide/libraries/uploaded_files.html
Your validation should be altered
$this->validate([
//... your other validations...
'image' => 'uploaded[image]' // instead of required
]);
If you want to store the image on your server and then record the name of the image in the database to retrieve later:
$imageDirectory="/path/to/where/you/store/images";
$imageName = $file->getRandomName();
$path = $this->request->getFile('image')->store($imageDirectory, $imageName);
// path is now the full path to the image on your server.
if you want to store the image BLOB data instead (like your example):
$tempfile = $file->getTempName();
$imgdata = file_get_contents($tempfile);
Then your insert would look like this...
$model->save([
'title' => $this->request->getPost('title'),
'slug' => url_title($this->request->getPost('title'), '-', TRUE),
'info' => $this->request->getPost('info'),
'image' => $imgdata,
]);

Update article laravel

Controller article
public function update(Request $request, Article $article){
$article->update($request->except('slug', 'image_path'));
if ($request->hasFile('image_path')) {
$image = $request->file('image_path');
$new_name = rand() . '.' . $image->getClientOriginalExtension();
$image->move(public_path('images'), $new_name);
$article->image_path = $new_name;
$article->save();
}
$article->categories()->detach();
if ($request->has('categories')) {
$article->categories()->attach($request->input('categories'));
}
$user=auth()->user();
return redirect()->back()->with('message', 'Raksts atjaunots!');
}
public function edit(Article $article){
$user=auth()->user();
return view('edit',[
'article' => $article,
'categories' => Category::with('children')->where('parent_id',0)->get(),
'delimiter' => ''
]);
}
edit blade
<form class="form-horizontal" action="{{route('update', $article)}}" method="post" enctype="multipart/form-data" style="display: flex;justify-content: center;flex-direction: column;">
<input type="hidden" name="_method" value="put">
{{ csrf_field() }}
{{-- Form include --}}
<img src="{{URL::to('/images').'/'.$article->image_path}}" alt="">
#include('partials.form')
<input type="hidden" name="modified_by" value="{{Auth::id()}}">
</form>
link to the form
<tbody>
#foreach ($articles_suggest_user as $article)
<a class="btn btn-default" href="{{route('edit', $article)}}"><i class="fa fa-edit"></i></a>
<?php } ?>
#endforeach
</tbody>
web.php
Route::get('/home/edit/{id}','Controller_Article_parents#edit', function () {
return view('/home/edit');
})->name('edit');
Route::get('/home/update/','Controller_Article_parents#update', function () {
return view('/home');
})->name('update');
When i clicked the link, i move to for example this url http://127.0.0.1:8000/home/edit/190
But my form is empty... input empty. How I can do when I open form it's display me input information ?
When click my link its display me form, but form is empty.
form example
<div class="rtq">
<label for="parent_id">Cat</label>
<span class="required">*</span>
<select
id="parent_id"
class="form-control"
name="categories[]"
multiple=""
required
>
#include('admin.categories.partials.categories',
['categories' => $categories,
'current' => $article,
'delimiter' => $delimiter])
</select>
</div>
<div class="rtq">
<label for="">Descript</label>
<textarea
name="description_short"
class="form-control"
id="description_short"
>
{{ $article->description_short ?? "" }}
</textarea>
</div>
It my form . Mini example
If you want to redirect with form input, you can use the withInput() function
return back()->withInput();
https://laravel.com/docs/7.x/redirects#creating-redirects
Now, this function is designed to be used with form validation and may not be what you want.
What I have done in the past when combining create & edit views into a single template is something like this:
{!! Form::text('name', isset($model) ? $model->name : null, [
'class' => 'form-control',
'placeholder' => 'Please fill out this field &hellips;',
'required' => true
]) !!}
This uses the Laravel Collective HTML library. However the principle is the same if you are using raw hmtl like so:
<input type="text" value="{{ isset($model) ? $model->name : null }}">
Round 2 Electric Boogaloo
You aren't returning a variable called $article to your edit.blade.php.
Round 3 Apple Tree
Originally, you appeared to be calling both a controller action AND also a callback function. Stick to the controller action only like so:
Route::get('/home/edit/{id}','Controller_Article_parents#edit')->name('edit');
Then within your edit() function on the Controller you will want to do this:
public function edit ($id) {
return view('/home/edit', [
'article' => Article::find($id)
]);
}

Laravel file upload without changing name

I want to upload a files to my laravel project. But I recognise that laravel randomly change my file name. How do I upload files to laravel without changing it's name. Also somehow my validation are not working. I just got redirected without any messages.
this are my blade
//show errors
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
/ul>
</div>
#endif
// forms
<form action="{{ route('designers.store') }}" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group d-flex flex-column">
<label for="exampleInputFile">File input</label>
<input type="file" name="files[]" multiple>
</div>
<button type="submit">Submit</button>
</form>
this are my controller
$data = $request->validate([
'project' => 'required|numeric',
'totalItem' => 'required|numeric',
'files' => 'file',
]);
if ($request->hasFile('files')) {
$allowedfileExtension=['pdf','jpg','png','docx','png','xlsx'];
$files = $request->file('files');
foreach ($files as $key => $value) {
$filename = $value->getClientOriginalName();
$extention = $value->getClientOriginalExtension();
$check = in_array($extention,$allowedfileExtension);
if ($check) {
File::create([
'name' => $value->store('designers','public'),
'type' => 'designer',
'project_id' => $data['project'],
'user_id' => Auth::user()->id,
]);
}
}
}
You can change your controller to this:
use Illuminate\Support\Facades\Storage;
function yourFunction(){
$this->validate($request,[
'project' => 'required|numeric',
'totalItem' => 'required|numeric',
'files' => 'nullable|array|file|mimes:pdf,jpg,png,docx,xlsx' //This validates file and MIME type. Also if it is not required, it should perhaps be nullable.
]);
if($request->hasFile('files'){
$files = $request->file('files');
foreach($files as $file){
$filename = $file->getClientOriginalName();
Storage::disk('local')->put($filename, file_get_contents($file)); //This stores your file.
}
}
//Save stuff to DB here
}
Official doc on file storage: https://laravel.com/docs/5.8/filesystem
Official doc on Validation of MIME: https://laravel.com/docs/5.8/validation#rule-mimes

Laravel 5.1 File Upload isValid() on string?

So I am making a function for file uploading in my project.
however, when I try it I get this error : Call to a member function isValid() on string
My code for the upload function :
public function upload(Request $request){
$file = array('profielfoto' => $request->input('profielfoto'));
$rules = array('profielfoto' => 'required',);
$validator = Validator::make($file,$rules);
if($validator->fails()){
return redirect('/profiel')->withInput()->withErrors($validator);
}
else{
if($request->input('profielfoto')->isValid()){ //<- gives error
$destinationPath = 'assets/uploads';
$extension = $request->input('profielfoto')->getClientOriginalExtension();
$fileName = rand(1111,9999).'.'.$extension;
$request->input('profielfoto')->move($destinationPath,$fileName);
Session::flash('alert-success', 'Foto uploaden gelukt');
return redirect('/profiel');
}
else{
Session::flash('alert-danger', 'Foto uploaden mislukt');
return redirect('/profiel');
}
}
}
The form in the blade view on the 4th line from down below is the location for the input!
<form method="POST" action="/profiel/upload" files="true">
{!! csrf_field() !!}
<input type="hidden" name="_method" value="PUT">
<input type="hidden" class="form-control id2" id="id2" name="id" value="{{$user->id}}">
<img src="assets/images/avatar.png" alt="gfxuser" class="img-circle center-block">
<div class="form-group center-block">
<label class="center-block text-center" for="fotoinput">Kies uw foto</label>
<input class="center-block" type="file" name="profielfoto" id="profielfoto">
</div>
<button type="submit" class="btn btn-success"><span class="fa fa-check" aria-hidden="true"></span> Verander foto</button>
</form>
You must ask isValid() to a file, not to the name of the file. That's why you get the error. You can get the file through $request->file() or through Input::file() :
else{
if( $request->file('profielfoto')->isValid()){ //<- gives error
Also your form should include the correct enctype to send files:
<form enctype="multipart/form-data">
I think you should use as this.
$file = $request -> file('Filedata');
if (!$file -> isValid()) {
echo Protocol::ajaxModel('JSEND_ERROR', 'not an valid file.');
return;
}
Add attribute on
enctype="multipart/form-data"

Categories