我有一种奇怪的情况,其中数据以json格式而不是html显示! 在路线http://127.0.0.1:8000/addpost中,显示要添加帖子的表单,以及最近添加的帖子。
它显示要添加帖子的表单,单击提交后,它将以json格式返回数据,而不显示表单和添加的帖子。 1)为什么返回json数据? 2)如何显示html格式的数据? 那就是我的路线
web.php
Route::get('addpost','PostController@index');
Route::post('addpost','PostController@store');
控制器->
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');
}
}
和视图
<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>
答案 0 :(得分:1)
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='';
}