How to display the user in comment - php

I have a comment box in my app and its working fine. but i want to display the user who comment in my post how can i achieve this? i have this code so far.
This is my view
<div class="view-post">
<div class="body">
<h3>{{$posts->title}}</h3>
<h6>{{$posts->created_at->toFormattedDateString()}}</h6>
<p><img src="{{ asset('img/' . $posts->image) }}" class="img-rounded"/></p>
<p>{{$posts->content}}</p>
</div>
<hr>
<section>
<h5>LEAVE US A COMMENT</h5>
<form action="{{ URL::route('createComment', array('id' => $posts->id))}}" method="post">
<div class="form-group">
<input class="form-control" type="text" placeholder="Comment..." name="content">
</div>
<input type="submit" class="btn btn-default" />
</form>
</section><br>
<section class="comments">
#foreach($posts->comment as $comments)
<blockquote>{{$comments->content}}</blockquote>
#endforeach
</section>
</div>
My Controller
public function viewPost($id)
{
$post = Post::find($id);
$user = Auth::user();
$this->layout->content = View::make('interface.viewPost')->with('posts', $post )->with('users',$user);
}
public function createComment($id)
{
$post = Post::find($id);
$comment = new Comment();
$comment->content = nl2br(Input::get('content'));
$post->comment()->save($comment);
return Redirect::route('viewPost', array('id' => $post->id));
}

In your model you can set up relations between one and another model.
Like that..
User Model
class User extends Model {
public function comments()
{
return $this->hasMany('App\Comment');
}
}
Comment Model
class Comment extends Model {
public function user()
{
return $this->belongsTo('App\User');
}
}
So you can get the user with
$comment = Comment::find(1);
$user = $comment->user()->get();

Related

Resource Controller Concept

I am unable to find the issue. It is showing 404|Not Found
update.blade.php
#extends('main')
#section('content')
<h1>Update Post</h1>
<form method="POST" action="{{route('posts.update', $post) }}" >
#method('PUT')
#csrf
<input type="text" name="title"><br><br>
<input type="text" name="body"><br><br>
<button type="submit" class="btn btn-primary">Update</button>
</form>
#endsection
PostController.php (a resource controller)
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\posts;
use Sessions;
class PostController extends Controller
{
public function index()
{
$post = posts::all();
return view('post.index', compact('post');
}
public function create(Request $req)
{
return view('posts.create');
}
public function store(Request $request)
{
$post = new posts;
$post->title = $request->input('title');
$post->body = $request->input('body');
$post->save();
return redirect('/');
}
public function show($data)
{
$post = posts::findOrFail($data);
return view('posts.read', compact('post','$post'));
}
public function edit(posts $post)
{
return view('posts.edit', compact('post'));
}
public function update(Request $request, $id)
{
$request->validate([
'title'=>'required',
'body'=>'required'
]);
$post = posts::find($id);
$post->title = $request->get('title');
$post->body = $request->get('body');
$post->save();
return redirect('/');
}
}
route:
Route::resource('posts', 'PostController');
please tell me what is the issue in this.
one of the advice I got is to change the name of view file i.e update.blade.php to edit.blade.php. I don't know how does it help
The problem is that you are returning the view: view('post.edit').
But you say that the file is called update.blade.php.
So you will have to rename the file to edit.blade.php or you need to change your edit function as follows, so that it returns the update blade file:
public function edit(posts $post)
{
return view('posts.update', compact('post'));
}
First you should change edit.blade.php instead of update.blade.php
Second you should not call model like this use App/posts; It is wrong. It must be use App\Post; in your PostController
Third you should change edit() in your controller
public function edit($id)
{
$post = Post::find($id);
return view('posts.edit', compact('post'));
}
You should use $post->id instead of $postin your form action
#extends('main')
#section('content')
<h1>Update Post</h1>
<form method="POST" action="{{route('posts.update', $post->id) }}" >
#method('PUT')
#csrf
<input type="text" name="title"><br><br>
<input type="text" name="body"><br><br>
<button type="submit" class="btn btn-primary">Update</button>
</form>
#endsection
Then check
public function update(Request $request, $id)
{
dd($id);//check id before update
$request->validate([
'title'=>'required',
'body'=>'required'
]);
$post = posts::find($id);
$post->title = $request->get('title');
$post->body = $request->get('body');
$post->save();
return redirect('/');
}

Edit page show blank in laravel

I have news details inserted and i need to show it on the edit page but when i try to edit and delete it shows blanks page insert and show is working properly. i have been stucked on this from morning. id is getting from the database but it shows a blank page,Not using any Form helper
1.what's problem,is it on route file
2.is it on Controller file
route.php
Route::get('/', function () {
return view('welcome');
});
Route::resource('books','BookController');
Route::resource('news','NewsController');
Auth::routes();
Route::get('/news','NewsController#index')->name('news');
//Route::get('/news/create','NewsController#create');
//Route::get('/news/edit','NewsController#edit');
Edit.blade.php
#extends('theme.default')
#section('content')
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
NEW BEE NEWS DETAILS
</div>
<div class="panel-body">
<div class="row">
<div class="col-sm-12">
<form method="post" action="{{route('news.update',[$news->id])}}"
enctype="multipart/form-data">
{{csrf_field()}}
<input type="hidden" name="_method" value="put">
<div class="form-group">
<label>NEWS TITLE</label>
<input type="text" name="atitle" id="atitle" class="form-control"
placeholder="PLEASE ADD TITLE OF NEWS" value="{{$news->name}}">
<p class="help-block">Example: SELFY PLAYSHARE </p>
</div>
<div class="form-group">
<label>NEWS</label>
<textarea name="news" id="news" class="form-control" {{$news->news}}></textarea>
<p class="help-block">DETAILED NEWS HERE</p>
</div>
<div class="form-group">
<label>NEWS LINK</label>
<input type="text" name="alink" id="alink" class="form-control"
placeholder="PLEASE ADD LINK OF NEWS" value="{{$news->alink}}">
<p class="help-block">Example: https://play.google.com/store/apps/selfyplusure</p>
</div>
<div class="form-group">
<label>NEWS IMAGE</label>
<input type="file" name="addimage" id="addimage" value="{{$news->imagename}}">
</div>
<button type="submit" class="btn btn-default">ADD NEWS</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
NewsController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use App\News;
use Illuminate\Http\Request;
class NewsController extends Controller
{
public function index()
{
$news = News::all();
return view('news.index', ['news' => $news]);
}
public function create()
{
return view('news.create');
}
public function store(Request $request)
{
$news=new News();
if($request->hasFile('addimage')){
$request->file('addimage');
$imagename=$request->addimage->store('public\newsimage');
$news->name = $request->input('atitle');
$news->alink = $request->input('alink');
$news->news = $request->input('news');
$news->imagename = $imagename;
$news->save();
if($news) {
return $this->index();
} }
else{
return back()->withInput()->with('error', 'Error Creating News ');
}
}
public function show(News $news)
{
//
}
public function edit(News $news)
{
$news=News::findOrFail($news->id);
return view('news.edit',['News'=>$news]);
}
public function update(Request $request, $id)
{
$news = News::findOrFail($id);
// update status as 1
$news->status = '1';
$news->save();
if ($news) {
// insert datas as new records
$newss = new News();
//On left field name in DB and on right field name in Form/view
$newss->name = $request->input('atitle');
$newss->alink = $request->input('alink');
$newss->news = $request->input('news');
$newss->imagename = $request->input('addimage');
$newss->save();
if ($newss) {
return $this->index();
}
}
}
public function destroy($id)
{
$news = News::findOrFail($id);
$news->status = '-1';
$news->save();
if ($news) {
return $this->index();
}
else{
return $this->index();
}
}
}
Link to delete and Edit
<td><input type="button" name="edit" value="EDIT">
<td><input type="button" name="delete" value="DELETE"></td>
This is the link to edit
<td><input type="button" name="edit" value="EDIT">
For delete please go through
Delete
In your controller try to use this.
return view('news.edit',compact('news'));

Undefined variable:user laravel

I keep on getting this error whenever I try to enter the upload page.
Can anybody help?
I have already done the compact part to make sure that the variable is being passed to the view and also my route should be ok I think.
I tried using dd but all it does is keep on showing me the error
Error: Undefined variable: user (View: C:\xampp\htdocs\Evaluation\resources\views\upload.blade.php)
Here are my codes:
upload.blade.php
<form class="form-horizontal" method="post" action="{{ url('/userUpload')}}" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="hidden" name="user_id" value="{{$user->id}}">
<div class="form-group">
<label for="imageInput" class="control-label col-sm-3">Upload Image</label>
<div class="col-sm-9">
<input type="file" name="file">
</div>
</div>
<div class="form-group">
<div class="col-md-6-offset-2">
<input type="submit" class="btn btn-primary" value="Save">
</div>
</div>
</form>
UploadController:
public function upload(){
return view(‘upload’);
}
public function store(Request $request,$id){
$this->validate($request, [
'file' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
var_dump('has file '.$request->hasFile('file'));
if ($request->hasFile('file')) {
$image = $request->file('file');
$name = $image->getClientOriginalName();
$size = $image->getClientSize();
$id = $request->user_id;
$destinationPath = public_path('/images');
$image->move($destinationPath, $name);
$Image = new Image;
$Image->name = $name;
$Image->size = $size;
// $Image->user_id = $id;
//$Image->save();
$user->find($id);
dd($user);
$user->Images()->save($Image);
}
return redirect('/home');
}
public function test(){
$user = user_information::where('id')->get();
return view('upload', compact('user'));
}
Route: (this are my route)
Route::get('/UploadUser/upload','UploadController#upload’);
Route::post('/UploadUser','UploadController#store');
Route::post('/UploadUser/upload', 'UploadController#test');
Another question: I keep on getting this error when i try to upload a file, so what should I do?
Here is the error:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or
update a child row: a foreign key constraint fails (form.images,
CONSTRAINT images_user_id_foreign FOREIGN KEY (user_id) REFERENCES
usere_information (id)) (SQL: insert into images (name,
size, user_id, updated_at, created_at) values (download.png,
4247, 1, 2017-10-25 08:54:57, 2017-10-25 08:54:57))
Image model:
class Image extends Model
{
protected $fillable = array('name','size','user_id');
public function user_informations() {
return $this->belongsTo('App\user_information', 'user_id', 'id');
}
}
Images table:
Schema::create('images', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('size');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('user_informations');
$table->timestamps();
});
User_information table:
Schema::create('user_informations', function (Blueprint $table) {
$table->increments('id');
$table->engine = 'InnoDB';
$table->binary('signature');
$table->String('Name');
$table->timestamps();
});
User_information model:
class user_information extends Eloquent
{
protected $fillable = array('signature', 'Name');
protected $table = 'user_informations';
protected $primaryKey = 'id';
public function Images() {
return $this->hasOne('App\Image','user_id');
}
}
How to get the image?
Here is the view folder:
#foreach ($data as $object)
<b>Name: </b>{{ $object->Name }}<br><br>
Edit<br>
#foreach ($data3 as $currentUser)
<img src="{{ asset('public/images/' . $currentUser->Image->name ) }}">
#endforeach
#if($data3->count())
#foreach($data3 as $currentUser)
<a href="{!! route('user.upload.image', ['id'=>$currentUser->user_id]) !!}">
<button class="btn btn-primary"><i class ="fa fa-plus"></i>Upload Images</button>
</a>
#endforeach
#else
<a href="{!! route('user.upload.image', ['id'=>$object->id]) !!}">
<button class="btn btn-primary"><i class ="fa fa-plus"></i>Upload Images</button>
#endif
#endforeach
HomeController:
public function getInfo($id) {
$data = user_information::where('id',$id)->get();
$data3=Image::where('user_id',$id)->get();
return view('test',compact('data','data3'));
Because you didn't pass the user to your upload view, try to pass it like this :
public function upload(){
$id = 1 //The wanted user or if the user is authenticated use Auth::id()
$user = User::find($id);
return view('upload')->withUser($user);
}
Or if the user is authenticated use Auth in the view :
<form class="form-horizontal" method="post" action="{{ url('/userUpload')}}" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="hidden" name="user_id" value="{{auth()->id()}}">
<div class="form-group">
<label for="imageInput" class="control-label col-sm-3">Upload Image</label>
<div class="col-sm-9">
<input type="file" name="file">
</div>
</div>
<div class="form-group">
<div class="col-md-6-offset-2">
<input type="submit" class="btn btn-primary" value="Save">
</div>
</div>
</form>
For the second problem it's because in the route you have
Route::post('/UploadUser','UploadController#store');
and the your store method signature is
public function store(Request $request,$id){
The $id parameter that did the problem because it's not defined in the route so simply remove it from the method signatre
public function store(Request $request){
$this->validate($request, [
'file' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
if ($request->hasFile('file')) {
$image = $request->file('file');
$name = $image->getClientOriginalName();
$size = $image->getClientSize();
$id = $request->user_id; // here id is declared no need for the parameter
$destinationPath = public_path('/images');
$image->move($destinationPath, $name);
$Image = new Image;
$Image->name = $name;
$Image->size = $size;
$Image->user_id = $id;
$Image->save();
}
return redirect('/home');
}
For the third case you have to change the routes from :
Route::get('/UploadUser/upload','UploadController#upload’);
to
Route::get('/UploadUser/{user}/upload','UploadController#upload’)->name('user.upload.image');
And in the view add the id in the upload button url maybe like this :
{!! route('user.upload.image', ['user'=>$currentUser->id]) !!}
Then in the upload method :
public function upload(user_information $user){ // route model binding here
// dd($user); //for testing only :)
return view('upload')->withUser($user);
}
In the view change
<input type="hidden" name="user_id" value="{{auth()->id()}}">
To
<input type="hidden" name="user_id" value="{{$user->id()}}">
And you are good to go ;)
#foreach ($data as $currentUser)
<b>Name: </b>{{ $currentUser->Name }}<br><br>
Edit<br>
#if($currentUser->Image)
<img src="{{ asset('public/images/' . $currentUser->Image->name ) }}">
#endif
<a href="{!! route('user.upload.image', ['id'=>$currentUser->id]) !!}">
#endforeach
You have miss to pass id in your where condition,
public function test(){
$user = user_information::where('id',$id)->first();
return view('create1', compact('user'));
}
and you have to pass your user data into this,
public function upload(){
$user = user_information::where('id',$id)->first();
return view(‘upload’,compact('user'));
}
Hope it helps,
On your upload function, you have to pass the user variable because you use the $user in the view. So the controller will be
public function upload() {
$user = Auth::user();
return view('upload', compact('user'));
}
do not forget to change the $user based on your need.
You have to pass an $id variable into your test() method. Then please comment below what's the error next so I can follow you through.
Update
Since you don't want to pass an id. You can use:
public function test(){
$u = Auth::user();
$user = user_information::where('id', $u->id)->get();
return view('upload', compact('user'));
}
OR
Try to use first() instead of get().
More option:
I have noticed, you're using the upload() method here, why not passing the $user there? like so:
public function upload(){
$user = Auth::user();
return view(‘upload’, compact('user'));
}

Product search function not working in CodeIgniter

I tried to make a function in the CodeIgniter framework so users can search products from my database and display (echo) them if a certain product is found.
The problem is if I try to search for a keyword I see a blank page and nothing happens.
Search controller:
<?php
class SearchController extends CI_Controller {
public function index(){
$data = array();
//load view
$this->load->view('result_view',$data);
}
function search_keyword()
{
$this->load->model('Search_model');
$keyword = $this->input->post('keyword');
$data['results'] = $this->Search_model->search($keyword);
}
}
My search model:
<?php
class Search_model extends CI_Model {
function search($keyword) {
$this->db->select('product_naam');
$this->db->like('product_naam',$keyword);
$query = $this->db->get('products');
return $query->result();
}
}
?>
My view file:
<h2>Zoek een cadeau</h2><br>
<form class="navbar-form" role="search" action="<?= base_url('SearchController/search_keyword')?>" method = "post">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search" name = "keyword" size="30px; ">
<div class="input-group-btn">
<button class="btn btn-default " type="submit" value = "Search"><i class="glyphicon glyphicon-search"></i></button>
</div>
</div>
</form>
</center>
<div class="clearfix"></div>
Change
return $query->result();
to
return $query->result_array();
Also, you are not calling result page in function and passing data in view.
function search_keyword()
{
$this->load->model('Search_model');
$keyword = $this->input->post('keyword');
$data['results'] = $this->Search_model->search($keyword);
$this->load->view('result_view',$data);
}

ErrorException (E_ERROR) HELP Array to string conversion (View: C:\xampp\htdocs\blog50\app\views\blog\view.blade.php)

//this is the view.blade.php file. it is showing the above error can any one please give ideas whats going wrong . the Route. php file and the blog controller.php is given below. ,maybe the the problem is in controller or route file , i dont know.
///view.blade.php
#section ('content')
#include('blog.partials.post', array('post'=> $post))
<hr/>
<section id="comments">
#foreach($post->comments as $comment)
<div class="comment">
<p>{{$comment->name }} says...</p>
<blockquote>
{{$comment->comment}}
</blockquote>
</div>
#endforeach
</section>
<section>
<h3 class="title">Add a Comment..</h3>
<form action="{{ URL::route('createComment'), array('id'=>$post->id)}}" method="POST">
<div class="form-group" >
<input type="text" name="name" placeholder="your name" class="form-control">
</div>
<div class="form-group" >
<textarea class="form-control" name="content" placeholder="your comment">
</textarea>
</div>
<input type="submit" class="btn btn-primary" value="Add Comment">
</section>
#stop
///route.php
Route::get('/', 'BlogController#index');
Route::get('post/new', array(
'uses'=>'BlogController#newPost',
'as' =>'newPost',
));
Route::post('/post/new' ,array(
'uses' =>'BlogController#createPost',
'as' =>'createPost',
));
Route::get('post/{id}',array(
'uses' =>'BlogController#viewPost',
'as' =>'viewPost',
));
Route::post('/post/{id}/comment',array(
'uses'=>'BlogController#createComment',
'as' =>'createComment'
));
////BlogController
class BlogController extends BaseController {
// set this controller's layout
protected $layout = 'layouts.master';
public function index()
{
$this->layout->content = View::make('blog.index',array(
'posts'=>Post::all()
));
}
// TODO: implement all the function we need in this controller
public function newPost()
{
$this->layout->content = View::make('blog.new');
}
public function createPost()
{
$post= new Post();
$post->title=Input::get('title');
$post->content=nl2br(Input::get('content'));
$post->save();
return Redirect::route('viewPost', array('id'=>$post->id));
}
public function viewPost($id)
{
$post = Post::findOrFail($id);
$this->layout->content = View::make('blog.view',array(
'post' =>$post
));
}
public function createComment($id)
{ $post = Post::findOrFail($id);
$Comment= new Comment();
$Comment->name=Input::get('name');
$Comment->content=nl2br(Input::get('content'));
$post->Comments()->save();
return Redirect::route('viewPost',array('id'=>$post->id));
}
}
Your parameter should be like this
<form action="{{ URL::route('createComment', array('id'=>$post->id))}}" method="POST">
Note : laravel blade template {{}} is equivalent to echo so now your passing parameter outside . so it's trying to echo the array . so here echo can't echo the array variable . that's why it's gave this error.
Array to string Conversion

Categories