Reputation: 17
i have weird situation in which data is displayed in json format instead of html !! At route http://127.0.0.1:8000/addpost form to add post is displayed and the recently added post.
Its show the form to add post and when submit is clicked it returns data in json format insteaad of displaying the form and the post added. 1)why it is returning json data ? 2)how do i display data in html format ? thats me route
web.php
Route::get('addpost','PostController@index');
Route::post('addpost','PostController@store');
Controller ->
PostController.php
class PostController extends Controller
{
public function index()
{
$posts = Post::latest()->first();
return view('addpost',compact('posts'));
}
public function store(Request $request)
{
$post =new Post();
$post->title= $request->input('title');
$post->body= $request->input('body');
if($request->hasfile('postimage'))
{
$file=$request->file('postimage');
$extention=$file->getClientOriginalExtension();
$filename=time().'.'.$extention;
$file->move('uploads/post',$filename);
$post->postimage=$filename;
}
else{
return $request;
$post->postimage='';
}
$post->save();
return back()->with('success', 'Your images has been successfully Upload');
}
}
and the view
<div class="container">
<div class="jumbotron">
@if(Auth::user())
<h3> Add new post with images</h3>
<form action="{{url('addpost')}}" method="POST" enctype="multipart/form-data">
{{csrf_field()}}
<div class="form-group">
<label>Title</label>
<input type="text" name="title" class="form-control" >
</div>
<div class="form-group">
<label>Body</label>
<input type="text" name="body" class="form-control" >
</div>
<div class="input-group">
<div class="custom-file">
<input type="file" name="image" class="custom-file-input">
<label class="custom-file-label">Choose file</label>
</div>
</div>
<button type="submit" name="submit" class="btn-brn-primary"> Save Post</button>
@if($posts)
@foreach($posts as $post)
<tr>
<td>{{$post->id}}</td>
<td>{{$post->title}}</td>
<td>{{$post->body}}</td>
<!-- <td><img src="{{asset('uploads/post/'.$post->image)}}" style="height: 150px;"></td>
<td><a href="">EDIT</a></td> -->
</tr>
@endforeach
@endif
@else
<h1>no</h1>
@endif
</form>
</div>
</div>
Upvotes: 0
Views: 81
Reputation: 794
if($request->hasfile('postimage')) // -> you are checking for postimage, in your html
// markup the file filed is called "image",
// therefore you will never enter this if block
{
$file=$request->file('postimage');
$extention=$file->getClientOriginalExtension();
$filename=time().'.'.$extention;
$file->move('uploads/post',$filename);
$post->postimage=$filename;
}
else{
return $request; // here you are returning the $request object that
// causes your unformatted response
$post->postimage='';
}
Upvotes: 1