How to get/input id from another field? - php

before that, I wanted to make a web app like google classroom. (in this case the Join Classroom section).
The result of my code is:
"Object of class Illuminate \ Database \ Eloquent \ Builder could not
be converted to string"
View:
<form action="{{ route('user.classroom.joinclassroom') }}">
#csrf
<label class="sr-only">Classroom Code</label>
<div class="input-group">
<input method="post" type="text" name="classroom_code" class="form-control" placeholder="eg.XIRPL301 | Max 8 Char/Num" aria-label="Recipient's username" aria-describedby="basic-addon2">
<div class="input-group-append">
<button name="submit" class="btn btn-sm btn-gradient-primary" type="submit">Search</button>
</div>
</div>
</form>
#foreach($classrooms->chunk(4) as $items)
<div class="row">
#foreach($items as $p)
<div class="col-md-4 stretch-card grid-margin">
<div class="card bg-gradient-danger card-img-holder text-white">
<div class="card-body">
<img src="{{ asset('classofus_resource/images/dashboard/circle.svg') }}" class="card-img-absolute" alt="circle-image"/>
<h4 class="font-weight-normal mb-3">{{ $p->name }}
<i class="mdi mdi-account-multiple mdi-24px float-right"></i>
</h4>
<h4 class="mb-5" data-toggle="tooltip" title="{{ $p->description }}">{{ str_limit($p->description, 32) }}</h4>
<form method="post" action="{{ route('user.classroom.joinclassroombutton') }}">
#csrf
<button type="submit" name="submit" class="btn btn-gradient-primary btn-sm">Join</button>
</form>
</div>
</div>
</div>
#endforeach
</div>
#endforeach
Relationship:
Many to Many
Enrollment Controller:
public function searchclassroom(Request $request)
{
$this->cari = $request -> classroom_code;
$classrooms = Classroom::wherein('classroom_code', [$this->cari]) -> get();
return view('pages.user.classroom.joinclassroom',['classrooms' => $classrooms]);
}
/* --------------------------------------- End Of Search Classroom -------------------------------------------- */
/* --------------------------------------- Join Classroom Button ----------------------------------------- */
public function joinclassroombutton(request $request)
{
$enrollment = Enrollment::create([
"classroom_id" => Classroom::select('id')->where('classroom_code', $this->cari),
'user_id' => Auth::user()->id
]);
}
And the point is, how is the syntax for getting classroom id with value with classroom_code? please help me ...

The problem is here, where you getting your classroom ID. You want to get ID, but you've got the Builder instance
"classroom_id" => Classroom::select('id')->where('classroom_code', $this->cari), // Builder
So, you can try:
"classroom_id" => Classroom::where('classroom_code', $this->cari)->first()->id, // just id of your model

Related

Missing required parameters for [Route: employees.update] laravel

i am creating crud in laravel.i ran into the problem with Missing required parameters for [Route: employees.update] [URI: employees/{employee}]. (View: C:\xampp\htdocs\jbs\resources\views\employees\edit.blade.php)what i tried so far i attach below. i added the model view controller below
Edit Blade Page
#extends('employees.layout')
#section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Edit Employee</h2>
</div>
<div class="pull-right">
<a class="btn btn-primary" href="{{ route('employees.index') }}"> Back</a>
</div>
</div>
</div>
#if ($errors->any())
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="{{ route('employees.update',$employees->id) }}" method="POST">
#csrf
#method('PUT')
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>StudentName:</strong>
<input type="text" name="name" value="{{ $employees->studname }}" class="form-control" placeholder="Name">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Course</strong>
<input type="text" name="name" value="{{ $employees->course }}" class="form-control" placeholder="course">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Fee</strong>
<input type="text" name="name" value="{{ $employees->fee }}" class="form-control" placeholder="fee">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 text-center">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
#endsection
Controller
public function edit(Employee $employees)
{
return view('employees.edit',compact('employees'));
}
public function update(Request $request, Employee $employees)
{
$request->validate([
'studname' => 'required',
'course' => 'required',
'fee' => 'required',
]);
$employees->update($request->all());
return redirect()->route('employees.index')
->with('success','Employee updated successfully');
}
Model
protected $fillable = [
'studname', 'course','fee',
];
}
routes
Route::resource('employees','App\Http\Controllers\EmployeeController');
Your route parameter is employee not employees. Route parameter names for resource routes are singular by default. The route is actually like this:
employees/{employee}
So in your edit method of your Controller you are using the wrong parameter name so you are getting a new instance of Employee instead of the Implicit Route Model Binding that would inject the instance based on the route parameter, you need to match the typehinted parameter name to the route parameter name:
// {employee}
public function edit(Employee $employee)
{
...
return view(...., ['employee' => $employee]);
}
Now in the view you will have your actual existing Employee instance that you can use to generate the URL to the route instead of an empty Employee that does not have an id which was returning null:
{{ route('employees.update', ['employee' => $employee->id]) }}
// or
{{ route('employees.update', ['employee' => $employee]) }}
The route system can get the correct key from the model instance.
You should pass $employees->id as a hidden input field.
Make your route as
Route::post('employee/update', 'YourController#yourFunction');
and in the edit page the form action should look like
<form action="{{ route('employees.update'}}" method="POST">
make a hidden input field for passing id
<input type="hidden" name="id" value="{{$employees->id}}"></input>
You should pass the route name to the route function like this
route('route name',parameter1)
Example :
Route::post('employee/update/{id}' ,YourController#update)->name('update_employee');
<form action="{{ route('update_employee',$employees->id) }}" method="POST">
#csrf
...

My code in laravel can't call back data from data base to update

Hello friends
I'm a new in laravel framework am trying to build a crud app so got this issue When i click Edit btn in the index page which calls data in specific ID to edit it well it shows "error 404 page not found" i still can't find where the problem is so please help
Product controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\product;
use Illuminate\Support\Facades\DB;
/*call product by specific id to update */
public function edit($id){
$product = DB::table('products')->where('id',$id)->first();
return view('product.edit',compact('product'));
}
/* product update */
public function update(request $request ,$id){
$oldlogo = $request->old_logo;
$data = array();
$data['product_name'] = $request->product_name;
$data['product_code'] = $request->product_code;
$data['product_details'] = $request->product_details;
$image = $request->file('product_logo');
if ($image){
unlink($oldlogo);
$image_name = date('dmy_H_s_i');
$ext = strtolower($image->getClientOriginalExtension());
$image_full_name = $image_name.'.'.$ext;
$upload_path = 'public/media/';
$image_url = $upload_path.$image_full_name;
$data['product_logo'] = $image_url;
$success =$image->move($upload_path,$image_full_name);
$data['product_logo'] =$image_url;
$product = DB::table('products')->where('id'.$id) -> update($data);
}
return redirect()->route('product.index')
->with('success','Product updated successfully');
}
edit btn`
<a class="btn btn-primary" href="{{ URL :: to ('edit/product'.$pro->id) }}">Edits</a>
edit page
#extends('product.layout')
#section('content')
<br><br><br>
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Edit Product</h2>
</div>
</div>
<br><br><br>
<div class="pull-right">
<a class="btn btn-success" href="{{ route('product.index') }}">Back</a>
</div>
<form action="" method="POST" enctype="multipart/form-data">
#csrf
<div class="form-row">
<div class="col-xs-12 col-xm-12 col-md-12">
<div class="form-group">
<strong>Product name</strong>
<input type="text" name="product_name" calss="form-control" value="{{ $product ->product_name }}">
</div>
</div>
<div class="col-xs-12 col-xm-12 col-md-12">
<div class="form-group">
<strong>Product Code</strong>
<input type="text" name="product_code" calss="form-control" value="{{ $product ->product_code }}">
</div>
</div>
<div class="col-xs-12 col-xm-12 col-md-12">
<div class="form-group">
<strong> Detials </strong>
<textarea class="form-control" name="Details" style="height:150px" >
{{ $product ->product_details" }}</textarea>
</div>
<div class="col">
<div class="form-group">
<strong>Product image</strong>
<input type="file" name="logo">
</div>
</div>
<div class="col">
<div class="form-group">
<strong>Product old image</strong>
<img src ="{{ URL::to($product->product_logo) }}" height="70px" width="80px" alt="logo">
<input type="hidden" name=" old_logo" value="{{ $product->product_logo }}">
</div>
</div>
<button type="button" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
#endsection
** edit Route **
Route::get('edit/product/{id}','ProductController#edit');
Route::post('update/product/{id}','ProductController#update');
laravel Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class product extends Model
{
protected $fillable = [
'product_name', 'product_details', 'product_code','product_logo'
];
}
I think your problem is right here: {{ URL :: to ('edit/product'.$pro->id) }} because its going to print for example this: /edit.product23. What you want is /edit/product/23, so change your URL to {{ URL::to('edit/product/'.$pro->id) }} or {{ url('edit/product/'.$pro->id) }}. Also make sure you set the route like this Route::get('/edit/product/{id}, 'ControllerName#edit'); in your web.php route file.

updating the data in pivot table laravel 5

i have a many to many realtionship and a pivot table now i want to update the pivot table data with a form that users sends. here for example is assign a client to a sellman . here is my code :
in route :
Route::get('admin/client/assign','ClientController#assignsellman');
controller :
public function assignsellman(Request $request){
$user = User::all();
$client_list = Client::all();
$client = Client::with('sellmanlist')->firstOrFail();
$sellman = $request->input('sellman');
$client->sellmanlist()->attach($sellman);
return view('admin.client.assign',compact('client_list','user'));
}
and finally here is the form of view file that i want to get 2 variables one the id of the client and the secound the id of sell man
<form action="/admin/client/" method="post">
<input type="hidden" name="_method" value="PUT">
{{ csrf_field() }}
<div class="row">
<div class="col-xs-4">
<div class="form-group">
<label for="client">مشتری</label>
<select class="select-search select2-hidden-accessible" tabindex="-1" aria-hidden="true"
name="client">
#foreach($client_list as $client_lists)
<option value="">{{$client_lists->title}}</option>
#endforeach
</select>
</div>
</div>
<div class="col-xs-4 text-center">
<i class="icon-arrow-left7 mr-3 icon-3x" style="font-size: 130px"></i>
<h4>ارجاع به</h4>
</div>
<div class="col-xs-4">
<div class="form-group">
<div class="form-group">
<label for="sellman">کارشناس فروش</label>
<select class="select-search select2-hidden-accessible" tabindex="-1"
aria-hidden="true" name="sellman">
#foreach($user as $users)
<option value="1">{{$users->name}}</option>
#endforeach
</select>
</div>
</div>
</div>
</div>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<button type="submit" class="btn btn-primary">تایید</button>
</form>
with this code i get this error
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
No message
thanks for help
Edit your route
Route::post('admin/client/','ClientController#assignsellman');
That is because the route you've created is HTTP GET, and in your form you're using HTTP Post.
<form action="/admin/client/" method="post">
Try switching to a GET method and it should work
<form action="/admin/client/" method="get">
or switch your route to
Route::post('admin/client/assign','ClientController#assignsellman');
Please take a look at the different HTTP Verbs and apply them to your needs.
https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

Laravel resource store method is being redirected to destroy method

I have a resource route
Route::resource('climb-excluded','CexcludedController',['only'=>['store','update','destroy']]);
And my code in view to save data
<div class="col-lg-4">
<form class="form" method="POST" action="{{ route('climb-excluded.store') }}">
{{ csrf_field() }}
<div class="card">
<div class="card-head style-primary">
<header>Add item</header>
</div>
<div class="card-body floating-label">
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<input type="text" class="form-control" id="name" name="name">
<label for="name">Name</label>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-10 col-sm-offset-1">
<button type="submit"
class="btn btn-block btn-success ink-reaction">
Add
</button>
</div>
</div>
</div>
</div>
A button to destroy data:
{!! Form::open( array('route'=>array('climb-excluded.destroy', $excluded->id),
'method'=>'DELETE')) !!}
<button type="submit"
class="btn ink-reaction btn-floating-action btn-sm btn-danger "
rel="tooltip"
title="Delete">
<i class="fa fa-trash-o" aria-hidden="true"></i>
</button
{!! Form::close() !!}
Store method form controller:
public function store(Request $request)
{
$this->validate($request,[
'name' => 'required|max:255'
]);
$excluded = new Cexcluded;
$excluded -> name = $request->name;
$excluded->save();
//redirect to
Session::flash('success','New item sucessfully added !');
return back()->withInput(['tabs'=>'second4']);
}
Destroy method form controller:
public function destroy($id)
{
$trekExcluded = Cexcluded::find($id);
$trekExcluded->tours()->detach();
$trekExcluded ->delete();
Session::flash('success','Item sucessfully deleted !');
return back()->withInput(['tabs'=>'second4']);
}
The trouble/bug that I'm facing is I can insert first row into table successfully. But when I go for the second one, the store method is somehow redirected to destroy method and deletes the first inserted row also. While I've clearly declared store method in action attribute of the form.
FYI: Both routes exists in same view/page. Destroy method in col-md-8with foreach loop while store method in col-md-4
Its quite obvious, that your form don't have a unique name or id, so that's why the second method is redirected to destroy method. Do something like this:
cex-store-1
cex-destroy-1

Eloquent $model->update() does not make changes on database record

When I update my comment it goes back to the page and changes the comment back to orignal, so the update hasn't been done. No errors or something.
db: comments
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->integer('articleID')->unsigned();
$table->string('comment');
$table->timestamps();
});
model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
protected $fillable = ['comment', 'articleID'];
public function article() {
return $this->belongsTo('App\Article');
}
}
CommentsController
public function edit($commentID) {
$comment = Comment::findOrFail($commentID);
return view('pages.comments.edit', compact('comment'));
}
public function update($commentID, CommentRequest $request) {
$comment = Comment::findOrFail($commentID);
$comment->update($request->all());
return view('/');
}
editComment view
<form action="{{ route('updateComments', ['commentID' => $comment->id]) }}" class="form-horizontal" method="get">
{{ csrf_field() }}
{{ method_field('PATCH') }}
<!-- Article data -->
<div class="form-group">
<label class="col-sm-3 control-label" for="body">Comment</label>
<div class="col-sm-6">
<textarea class="form-control" id="body" name="body" maxlength="1000">{{ $comment->comment }}</textarea>
</div>
</div>
<!-- Add Article Button -->
<div class="form-group">
<div class="col-sm-offset-3 col-sm-6">
<button class="btn btn-default" type="submit"><i class="fa fa-pencil-square-o"></i> Edit comment</button>
</div>
</div>
</form>
Your problem is:
You cannot do form submit with get method, even with hidden method_field('PATCH') in fact it does not event get to update action (:
Your form field name body is not correct if we look at fillable field of model
So just fix Your form:
<form
action="{{ route('updateComments', ['commentID' => $comment->id]) }}"
method="post"
class="form-horizontal">
{{ csrf_field() }}
<!-- Article data -->
<div class="form-group">
<label class="col-sm-3 control-label" for="comment">Comment</label>
<div class="col-sm-6">
<textarea
id="comment"
name="comment"
maxlength="1000"
class="form-control"
>{{ $comment->comment }}</textarea>
</div>
</div>
<!-- Add Article Button -->
<div class="form-group">
<div class="col-sm-offset-3 col-sm-6">
<button class="btn btn-default" type="submit">
<i class="fa fa-pencil-square-o"></i> Edit comment
</button>
</div>
</div>
</form>
or change Your schema and model to have field called body not comment
p.s. also fix Your update action:
public function update(CommentRequest $request, $commentID) {
$comment = Comment::findOrFail($commentID);
$comment->update($request->except(['articleID'])); // for safety we are ignoring "possible existence" of articleID in forma
return redirect(route('updateComments', compact('commentID')));
}
doing return view('/') is not correct - it's trying to find file with name / that of course does not exist.

Categories