Today I have made a comments system, but isn't completed.In my database I have all fields filled by dates, but user_id isn't.How can I be able to save in column user_id, the id of authenticated user?Here is my code.
CommentsController:
public function store(Request $request, $post_id)
{
$this->validate($request, array(
'username' => 'required|max:255',
'mail' => 'required|mail|max:255',
'comment' => 'required|min:5|max:2000',
));
$post = Post::find($post_id);
$comment = new Comment();
$comment->username = $request->username;
$comment->email = $request->email;
$comment->comment = $request->comment;
$comment->approved = true;
$comment->post()->associate($post);
$comment->save();
Session::flash('message', "Message posted successfully!");
return Redirect::back();
}
My view
<div class="row">
<div id="comment-form">
{{ Form::open(['route' => ['comments.store', $post->id], 'method' => 'POST']) }}
<div class="row">
<div class="col-md-6">
{{ Form::label('username', "Username:") }}
{{ Form::text('username', null, ['class' => 'form-control']) }}
</div>
<div class="col-md-6">
{{ Form::label('email', "Email:") }}
{{ Form::text('email', null, ['class' => 'form-control']) }}
</div>
<div class="col-md-6">
{{ Form::label('comment', "Comment:") }}
{{ Form::text('comment', null, ['class' => 'form-control']) }}
</div>
{{ Form::submit('Add Comment', ['class' => 'btn btn-success btn-xs']) }}
</div>
{{ Form::close() }}
</div>
My route
Route::post('comments/{post_id}', ['uses' => 'CommentsController#store', 'as' => 'comments.store']);
I tried to put Auth::user()->id inside my form, but I failed...
For you get the authenticated user you should only use the Auth facade. I show how to use it below.
use Illuminate\Support\Facades\Auth;
$user = Auth::user(); // Get the currently authenticated user...
$user_id = Auth::id(); // Get the currently authenticated user's ID...
Therefore, to save a user associated in a comment you have two options:
$user_id = Auth::id();
$comment->user_id = $user;
$comment->save();
Or
$user = Auth::user();
$comment->user = $user;
$comment->save();
If you have more questions about Laravel authentication take a look at https://laravel.com/docs/5.8/authentication#retrieving-the-authenticated-user.
Related
I am trying to insert data into the database neither it shows an error nor saves the data into my database below are the codes. here is the create blade php page .
#extends('layouts.app')
#section('content')
<h1>Create a Camp</h1>
<!-- if there are creation errors, they will show here -->
{{ HTML::ul($errors->all()) }}
{{ Form::open(array('url' => 'camps')) }}
<div class="form-group">
{{ Form::label('name', 'Name') }}
{{ Form::text('name', Request::old('name'), array('class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::label('district', 'District') }}
{{ Form::text('district', Request::old('district'), array('class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::label('address', 'Address') }}
{{ Form::text('address', Request::old('address'), array('class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::label('block', 'Block') }}
{{ Form::text('block', Request::old('block'), array('class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::label('population', 'population') }}
{{ Form::text('population', Request::old('population'), array('class' => 'form-control')) }}
</div>
{{ Form::submit('Create the Camp!', array('class' => 'btn btn-primary')) }}
{{ Form::close() }}
#endsection
here is the controller the index controller works fine when I manually enter the data it fetches from the database
here is the store controller and also it not validate the forms data , i am new i dont know how to do it
public function store(Request $request)
{
$rules = array(
'name' => 'required',
'district'=> 'required',
'address' => 'required',
'block' => 'required|numeric',
'Population' => 'required|numeric',
);
$validator = Validator::make(Request::all(), $rules);
if ($validator->fails()) {
return Redirect::to('camp/create')
->withErrors($validator)
->withRequest(Request::except('password'));
} else {
// store
$camp = new Camp;
$camp->name = Request::get('name');
$camp->district = Request::get('district');
$camp->address = Request::get('address');
$camp->block = Request::get('block');
$camp->population = Request::get('population');
$camp->save();
// redirect
Session::flash('message', 'Successfully created Camp!');
return view('camp\camps',['camps'=>$camps]);
}
}
You forgot to add parenthesis after Camp it should be like this:
$camp = new Camp();
$camp->name = $request->name;
$camp->district = $request->district;
$camp->save();
this is my form:
{!! Form::model($countries, ['route' => ['countries.update', $countries->id], 'method' => "PUT"]) !!}
{{ Form::label('code', 'Country Code:') }}
{{ Form::text('code', null, ['class' => 'form-control']) }}
{{ Form::label('name', 'Country Name:') }}
{{ Form::text('name', null, ['class' => 'form-control']) }}
{{ Form::submit('Save', ['class' => 'mt-20 btn btn-success btn-sm']) }}
{!! Form::close() !!}
and this is my update function:
$countries = Country::find($id);
$this->validate($request, array(
'code' => 'required|min:2|max:4',
'name' => 'required|max:255'
));
$country = Country::where('id',$id)->first();
$country->code = Input::get('code');
$country->name = Input::get('name');
$country->save();
Session::flash('success', 'The Country info was successfully updated.');
return redirect()->route('locations.index', $country->id);
what is the issue in my form that I'm getting Undefined variable: countries error from my blade?
Consolidating this answer from our conversation in the comments.
The error Undefined variable: countries in the blade view (form) arises as you have forgotten to pass the said variable to the view.
In the edit function (as this the function calling the view), add the following
$countries = Country::find($id); // though I'd suggest naming it $country
...
return view('<view_name>', compact('countries'));
I want this form to search multiple fields. How can I aggregate these search terms and filter them by their appropriate fields?
For example, if the user types "Book" into the textsearch field, and then selects "Assigned" from the status dropdown, the page should return all requests containing 'book' in the subject or details field, and 'assigned' in the status field.
I have the following form in my Laravel 4.2 Application:
{{ Form::open(['route' => 'requests.search']) }}
<!-- Text Search Form Input -->
<div class="form-group">
{{ Form::label('textsearch', 'Text Search:') }}
{{ Form::text('textsearch', $query, ['class' => 'form-control']) }}
{{ Form::hidden('search', 'text') }}
</div>
<!-- Status Form Input -->
<div class="form-group">
{{ Form::label('status', 'Status:') }}
{{ Form::select('status', $statuses, null, ['class' => 'form-control']) }}
</div>
<!-- Category Form Input -->
<div class="form-group">
{{ Form::label('category', 'Category:') }}
{{ Form::select('category', $categories, null, ['class' => 'form-control']) }}
</div>
<!-- Teamleader Form Input -->
<div class="form-group">
{{ Form::label('teamleader', 'Team Leader:') }}
{{ Form::select('teamleader', $projectmembers, null, ['class' => 'form-control']) }}
</div>
<!-- Requestid Form Input -->
<div class="form-group">
{{ Form::label('requestid', 'Request ID:') }}<br/>
<span>Between:</span>
{{ Form::text('requestidstart', null, ['class' => 'form-control', 'style' => 'width:100%;']) }}
<span>And:</span>
{{ Form::text('requestidend', null, ['class' => 'form-control', 'style' => 'width:100%;'])}}
</div>
<!-- Requestdate Form Input -->
<div class="form-group">
{{ Form::label('requestdate', 'Request Date:') }}<br/>
<span>From:</span>
{{ Form::text('requestdatestart', null, ['class' => 'form-control etadatepicker', 'style' => 'width:100%;']) }}
<span>To:</span>
{{ Form::text('requestdateend', null, ['class' => 'form-control etadatepicker', 'style' => 'width:100%;'])}}
</div>
<!-- Requestduedate Form Input -->
<div class="form-group">
{{ Form::label('requestduedate', 'Due Date:') }}<br/>
<span>From:</span>
{{ Form::text('requestduedatestart', null, ['class' => 'form-control etadatepicker', 'style' => 'width:100%;']) }}
<span>To:</span>
{{ Form::text('requestduedateend', null, ['class' => 'form-control etadatepicker', 'style' => 'width:100%;'])}}
</div>
{{ Form::submit('Search') }}
{{ Form::close() }}<br/>
Controller:
$requestresponsetype = ['' => ''] + RequestResponseType::lists('description', 'description');
$projectmembers = ['' => ''] + RequestProjectMember::lists('first_name', 'first_name');
$statuses = ['' => ''] + RequestStatus::lists('description', 'description');
$categories = ['' => ''] + RequestCategory::lists('description', 'description');
$query = Input::get('textsearch');
$requests = DataRequest::where("subject", "LIKE", "%$query%")->orWhere("details", "LIKE", "%$query%")->orWhere("id","LIKE","%$query%")->paginate(10);
return View::make('requests.index', ['requests' => $requests, 'statuses' => $statuses, 'requestresponsetype' => $requestresponsetype, 'projectmembers' => $projectmembers, 'categories' => $categories, 'query' => $query]);
I don't understand your idea clearly, but I guess something like:
$requests = DataRequest::where(function($q) {
$q->where("subject", "LIKE", "%$query%")
->orWhere("details", "LIKE", "%$query%")
->orWhere("id","LIKE","%$query%");
})
->where('status', '=', $status)
->paginate(10);
In my project, I created a scope to search, it's reuseable and readable.
//BaseModel
public function scopeSearch($query, $search, $fields)
{
$query->where(function($q) use ($search, $fields) {
foreach ($fields as $field) {
$q->orWhere($field, "LIKE", "%$search%");
}
}
}
$requests = DataRequest::search($query, ["subject", "details", "id"])
->where('status', '=', $status)
->paginate(10);
Hello im new in laravel 4.2 and i m making an application in the controllers, i made my own function called c_updateSystemUser($id) and here is the code
public function c_updateSystemUser($id)
{
//
session_start();
$getsCapt = $_SESSION["captcha"];
$rules = array(
'username' => 'required|min:2|max:50|regex:/^[a-zA-Z0-9\-\s]+$/|exists:dbo_systemusers,SystemUserName,$id',
'description' => 'required|min:1|max:100|regex:/^[a-zA-Z0-9\-\s]+$/',
'usertype' => 'required|numeric',
'capt' => 'required|numeric'
);
$validator = Validator::make(Input::all(), $rules);
// process the inputs given by the user
if ($validator->fails())
{
return Redirect::to('viewsu/' . $id)
->withErrors($validator)
->withInput(Input::except('password'));
}
else
{
// store the values into the database
$su = SystUser::find($id);
$su->SystemUserTypeID = Input::get('usertype');
$su->SystemUserName = Input::get('username');
$su->SystemUserDescription = Input::get('description');
$su->timestamps = false;
$su->save();
Session::flash('message', 'Successfully created system user!');
return Redirect::to('viewsu');
}
}
}
i wanted this function to be called when the user clicked the update button on my view file but when the button is clicked, it is redirecting to some other page (my create user page) i don't know why
here is the code of my form in my blade
{{ Form::model($su, array('route' =>array('csu.update',$su->SystemUserID),'method'=>'PUT'))}}
<div class="form-group">
{{ Form::label('usertype', 'User Type') }}
{{ Form::select('usertype', [null=>'Please Select user type'] + $sTyp , array('class'=>'form-control'))}}
{{ Form::label('current' , 'Current Type: (unedited) '.$su->SystemType , array('class' => 'label label-primary')) }}
</div>
<div class="form-group">
{{ Form::label('username', 'Username') }}
{{ Form::text('username', $su->SystemUserName, array('class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::label('description', 'Description') }}
{{ Form::textarea('description', $su->SystemUserDescription, array('class' => 'form-control','rows' => '3')) }}
</div>
<div class="form-group">
{{ Form::label('captcha', 'CAPTCHA image: ') }}
</br>
{{ HTML::image('http://localhost:8080/laravel3/app/captcha.php', 'alt' , array( 'width' => 200, 'height' => 35 )) }} </br></br>
{{ Form::text('capt', Input::old('capt'), array('class' => 'form-control','placeholder' => 'enter generated captcha')) }}
</div>
{{ Form::submit('Edit System User', array('class' => 'btn btn-primary')) }}
{{ Form::close()}}
i don't know how to make the form call the function public function c_updateSystemUser($id) in my controller
my controller file is called systemUsers.php
any ideas? any help would be appreciated
If your view name is update and its in views->csu folder you can do it like following
{{ Form::model($su, array('route' =>array('csu.update.c_updateSystemUser',$su->SystemUserID),'method'=>'PUT'))}}
#yourentry
{{Form::close()}}
Your route should be like following:
Route::resource('csu','systemUsers');
In systemUsers.php add c_updateSystemUser($id){} method.
I am new in laravel and I am trying to update users but I am stuck here. When I press the update button it does not do anything....
//HomeController.php
public function getUpdate($username) {
$user = array();
$users = User::where("username", "=", $username)->get();
foreach ($users as $key => $value) {
if (isset($value->username)) {
$user['username'] = $value->username;
$user['email'] = $value->email;
$user['password'] = $value->password;
}
}
$username = (object) $user;
return View::make('home.update', array('username' => $username));
}
public function postUpdate($username) {
$input = Input::all();
$rules = array('username' => 'required|unique:users',
'email' => 'required|unique:users|email',
'password' => 'required'
);
$v = Validator::make($input, $rules);
if ($v->fails()) {
Redirect::to('home.update')
->withErrors($v)
->withInput(Input::except('password'));
} else {
$user = User::find($username);
$user->username = Input::get('username');
$user->email = Input::get('email');
$user->save();
return Redirect::to('home.index')
->with('message', 'Successfully updated!');
}
}
//view
#extends('master')
#section('content')
<div class="span12 well" style="opacity: 0.9">
<h4>Update personal details:</h4>
{{ Form::open(array('url' => 'update/'.Auth::user()->username.'/update')) }}
#if($errors->any())
<div class="alert alert-error">
×
{{ implode('', $errors->all('<li class="error">:message</li>')) }}
</div>
#endif
<div class="form-group">
{{ Form::label('username', 'Username:') }}
{{ Form::text('username',$username->username, array('class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::label('email', 'E-mail:') }}
{{ Form::text('email', $username->email, array('class' => 'form-control')) }}
</div>
<p>{{ Form::submit('Update', array('class' => 'btn btn-success'))}}</p>
{{ Form::close() }}
</div>
#stop
//routes
Route::get('update/{username}', 'HomeController#getUpdate');
Route::post('update/{username}/update', 'HomeController#postUpdate');
Try this:
Change this:
{{ Form::open(array('url' => 'update/'.Auth::user()->username.'/update')) }}
Into:
{{ Form::open(array('url' => 'update/'.Auth::user()->id.'/update')) }}
Your route must be:
Route::post('update/{id}/update', 'HomeController#postUpdate');
And your controller must be:
public function postUpdate($id) { //I change this to id based on the url of your route
$input = Input::all();
$rules = array('username' => 'required|unique:users',
'email' => 'required|unique:users|email',
'password' => 'required'
);
$v = Validator::make($input, $rules);
if ($v->fails()) {
Redirect::to('home.update')
->withErrors($v)
->withInput(Input::except('password'));
} else {
$user = User::find($id); //User::find() only finds ID
$user->username = Input::get('username');
$user->email = Input::get('email');
$user->save();
return Redirect::to('home.index')
->with('message', 'Successfully updated!');
}
}