I have this form
<form method='POST' action='/products/{{ $product->id }}/reviews'>
{{ csrf_field() }}
<div>
<textarea name = 'review' placeholder ='Post a review'>{{ old('review') }}</textarea>
</div>
<div>
<button type ='submit'>Save</button>
</div>
</form>
The data then gets passed to this function in my controller
public function store(products $product)
{
$product->addReview(request('review'));
return back();
}
The addReview method is found in my products model
public function addReview($review)
{
return reviews::create([
'product_id' => $this->id,
'review' => $review
]);
}
I think the problem lies here
'product_id' => $this->id,
Once I fill in the form and submit, no data is added to the 'product_id' field. It's not included in any of the post data.
In your Review model:
public function product() {
return $this->belongsTo(products::class);
}
I renamed it to a product because it is one result not multiple.
Then here:
public function addReview($review)
{
return reviews::create([
'product_id' => $review->product->id,
'review' => $review
]);
}
Or even better, if you are adding a review, you should have the Product selected not the review, as you are adding a review to the product, so the method should be something like this:
public function addReview($product)
{
$review = request('review');
return $product->reviews()->create([
'review' => $review
]);
}
EDIT I see that you already have this.. so this code should work. If in the reviews table you have a product_id column, the relationship should be correct.
Related
I have a problem, i am doing a shift history of the user logged in the application.
#foreach($eventos as $evento)
if($evento->solicitud->users->id == (Auth::user()->id))
<div class="item-timeline">
<div class="t-meta-date">
<p class="">{{$evento->fecha}}</p>
</div>
<div class="t-dot">
</div>
<div class="t-text">
<p>{{$evento->servicio->servicio}}</p>
<p>{{$evento->personal}}</p>
</div>
</div>
#endif
#endforeach
I get all shifts with:
public function perfil (){
$eventos = Eventos::All();
$data = [
'category_name' => 'users',
'page_name' => 'profile',
'has_scrollspy' => 0,
'scrollspy_offset' => '',
];
// $pageName = 'profile';
return view('users.user_profile',compact('eventos'))->with($data);
}
Model Eventos:
public function solicitud()
{
return $this->belongsTo(Solicitudes::class);
}
Model Solicitudes:
public function evento()
{
return $this->belongsTo(Eventos::class);
}
and then filter with if condition.
But it shows me error Trying to get property 'users' of non-object
dd capture: https://i.imgur.com/WUVOaO6.png
data base: https://i.imgur.com/J5YSvxQ.png
I need to get the User_id from the solicitudes table.
The relation is: Eventos table-> solicitud_id with the ID column of the Solicitudes table.
from the code which you have provided, $evento-> solicitud-> users means I assume that you have used a nested relationship and the following things are missing
there is no 'users' relation in 'solicitudes' class
you didn't call relations in controller while fetching eventos (that is $eventos=Eventos::with('solicitud.users')->get()
correct me if my assumption is wrong
I am getting either of 2 errors one after the other.
While submitting the form either I get the error below
The page has expired due to inactivity. Please refresh and try again.
Or this error
InvalidArgumentException
Route [register/user/image] not defined.
I have cross checked everything unable to find out the real cause.
Routes/web.php
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::prefix('manage')->middleware('role:superadministrator|administrator|editor|member')->group(function() {
Route::get('/', 'ManageController#index');
Route::get('/carezone', 'ManageController#carezone')->middleware('role:superadministrator|administrator')->name('manage.dashboard');
Route::get('/dashboard', 'ManageController#dashboard')->name('manage.dashboard');
});
Route::middleware('role:superadministrator|administrator|editor|member|subscriber')->group(function() {
Route::get('register/user/details', 'RegisterUserController#showUserDetailsForm')->name('register.user.details');
Route::post('register/user/details', 'RegisterUserController#postUserDetailsForm')->name('register.user.details');
Route::get('/api/username/unique', 'RegisterUserController#apiCheckUniqueUserName')->name('api.username.unique');
Route::get('register/user/image', 'RegisterUserController#showUserImageForm')->name('register.user.image');
Route::post('register/user/image', 'RegisterUserController#postUserImageForm')->name('register.user.image');
});
Route::get('/email/unique', 'RegisterUserController#checkUniqueEmail')->name('email.unique');
Route::get('/get/city', 'RegisterUserController#ajaxGetCity')->name('get.city');
Route::get('/registration', 'RegisterUserController#showRegistrationForm')->name('registration');
Route::get('/home', 'HomeController#index')->name('home');
RegisterUserController.php
/*function to redirect user to user details page after register page*/
public function showUserDetailsForm() {
$states = State::all();
return view('pages.registration.registerUserDetails', ['states'=> $states]);
}
/*function to post and save data to the database*/
public function postUserDetailsForm(Request $request) {
$validatedData = $request->validate([
'username' => 'required|alpha_num|min:6|max:20|unique:details,username',
'dob' => 'required|date',
'gender' => 'required|string',
'state' => 'required|numeric',//validation rule for max min values
'city' => 'required|numeric',//validation rule for max min values
]);
$post = new Detail;
$post->user_id = Auth::user()->id;
$post->username = $request->username;
$post->dob = $request->dob;
$post->gender = $request->gender;
$post->state_id = $request->state;
$post->city_id = $request->city;
$post->save();
return redirect()->route('register/user/image');
}
Small Portion Of my form
<form id="registerUserDetails" class="form-horizontal clearfix" method="POST" action="{{ route('register.user.details') }}" role="form" novalidate>
{{ csrf_field() }}
.
.
.
.
<button type="submit" class="tabButton">Next</button>
</form>
<script>Javascript Validation here</script>
To solve the second error you must fix your route name on your controller method (and everywhere):
Actual:
return redirect()->route('register/user/image');
Correct:
return redirect()->route('register.user.image');
For solving the first error add the csrf field {{ csrf_field() }} to form
And for the second one, you route's name is register.user.image
so set the form's action like this
<form action=" {{ route('register.user.image') }} ">
I've been working on a webapp recently in laravel and i wanted to have a eddit function within tthe application. but im getting this error Missing required parameters for [Route: producten.update] [URI: producten/{producten}], and i dont know what i've done wrong.
This is the Routes im using:
Route::resource('producten', 'ProductenController', ['only' => ['index', 'store', 'update', 'delete', 'edit', 'destroy', 'create']]);
This is the controller function im using for showing the edit page and updating.
The Edit function
public function edit(Request $request, Product $product)
{
// $product = Product::FindorFail($id);
// Product is a table with all products, with sellprice and buy price
// fabriek = table that has a foreign key attached to the product table
return view('producten.edit', [
'model' => $product,
'fabrieks' => Fabriek::lists('Id')
]);
}
The Update Function:
public function update(Request $request, Product $product)
{
$product->update($request->all());
return redirect(Route('producten.index'));
}
and this is the view i use for it.
{{Form::model($model, ['method' => 'PATCH', 'action' => 'ProductenController#update', $model ]) }}
{{ Form::label('naam:')}}
{{ Form::text('naam') }} <br>
{{ Form::label('inkoopPrijs:')}}
{{ Form::text('inkoopPrijs') }} <br>
{{ Form::label('verkoopPrijs:') }}
{{ Form::text('verkoopPrijs') }} <br>
{{Form::label('Fabrieken', 'Fabrieken Id:') }}
{{ Form::select('Fabrieken_Id', $fabrieks)}} <br>
{{ Form::submit('edit')}}
{{ Form::close() }}
if there is anything else that i need to add to the question just let me know and i'll add it
Missing thing is the id you are not getting id there in your edit function
your edit function should as i am assuming that you are just showing the form from this method where user can edit
public function edit($id)
{
$product = Product::FindorFail($id);
//Product is a table with all products, with sellprice and buy price
//fabriek = table that has a foreign key attached to the product table
return view('producten.edit', [
'model' => $product,
'fabrieks' => Fabriek::lists('Id')
]);
}
your update method should seem like this
public function update(Request $request, $id)
{
$product->update($request->all());
return redirect(Route('producten.index'));
}
your routes should like this no need for only
Route::resource('/producten', 'productionController');
edit route will be as
<a href="{{ route('production.edit', $model->id) }}">
Try this hope it will help
On my page events.index, I first display a list of events for the logged on user.
On my index page I have a form with option/select to let the user select and display the events of another user. When he submits that form, I would like my index function (controller) to use the $user_id value (from the form) and display the events.index page again, but for events of that selected user.
I'm not sure what would be the best approach:
Set a session variable to keep the user_id value? Not sure how to do that with a form.
Submit the form with a get method (and get an ugly ?user_id=1 URL)
Change my index route to accept the post method (although I already have that post/events route taken (by Route::post('events', 'EventsController#store'))
Not sure what would be a clean way to do this:
My route for events/index:
Route::get('events', [
'as' => 'event.index',
'uses' => 'EventsController#index'
]);
Events Controller
public function index()
{
// How to get the $user_id value from form?
if (empty($user_id))
{
$user_id = \Auth::user()->id;
}
$events = Event::where('events.user_id','=','$user_id');
$users = User::all();
return view('events.index')->with(['events' => $events])->with(['users' => $users]);
}
View for index
{!! Form::open(['route' => 'events.index', 'method' => 'get']) !!}
<select id="user_id" name="user_id">
#foreach($users as $user)
<option value="{{$user->id}}">{{$user->name}}</option>
#endforeach
</select>
{!! Form::submit('Show events for this user') !!}
{!! Form::close() !!}
#foreach($events as $event)
...
#endforeach
You can get the user_id from a Request object, you just need to inject it in the index method:
public function index(Request $request)
{
$user_id = $request->get('user_id') ?: Auth::id();
$events = Event::where('events.user_id','=','$user_id')->get();
$users = User::all();
return view('events.index')->with(['events' => $events])->with(['users' => $users]);
}
I am using laravel 5. If the validation of any field fails, I want to get the value of a particular field from the request class which I have created and it can be displayed in the view class like displaying error messages. Does anyone knows how to code for that?
above photo, for the id part how to make the syntax to return the value?
Controller :
public function edit(Requests\EventRequest1 $request){
$date=$_POST['eventDate'];
$title=$_POST['title'];
$id=$_POST['id'];
$events=EventCal::findOrFail($id);
$events->update($request->all());
DB::table('event_cals')
->where('id',$id)
->update(['title' => $title,'eventDate' => $date]);
return redirect('/dcalendar');
}
Model :
class EventCal extends Model {
protected $fillable = [
'title',
'eventDate',
];
}
View :
#if($errors->has('title') )
<td><ul class="alert alert-danger" style="width: 250px;height: 40px"> {{$id}}</ul></td>
#endif
#if($errors->has('eventDate'))
<td><ul class="alert alert-danger" style="width: 250px;height: 40px"> {{$errors->first('eventDate')}}</ul></td>
#endif
EventRequest1(Request Class) :
public function rules()
{
return [
'title' => 'required',
'eventDate' => 'required|date|after:yesterday',
'id' => Request::get('id')
];
}
public function messages(){
return [
'title.required' => 'Title is required.',
'eventDate.after' => 'Event Date is passed.',
'eventDate.required' => 'Event Date is required.',
];
}
I want to return the id for view page. In the view page {{$id}} should print the id value.Is there any way? I'm not sure how to return the value of id from request. That's the only thing I needed to know.
Inside of your request class you must override the response() function:
public function response(array $errors)
{
return $this->redirector->back()
->withInput($this->except($this->dontFlash))
->withErrors($errors)
->with('id', $this->get('id'));
}