How to use the same form for add and edit in laravel - laravel

I'm new to laravel,i want to use the same form for add and edit.I created an form and form insertion is ok but i need to use the same form edit based on the id selected.When click the edit icon i want to direct the same page displaying the contents to edit.So give me idea for implementing this.
<form method="POST" action="/categoryinsert">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<div class="card-body">
<div class="form-group">
<div class="col-md-4">
<label for="exampleInputEmail1">Category</label>
<input type="text" class="form-control" name="category" id="category" placeholder="Enter Category">
</div>
</div>
<div class="card-footer">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>

// To create a new user in controller
public function create()
{
// user/createOrUpdate.blade.php view
return View::make('user.createOrUpdate');
}
// To update an existing user
public function edit($id)
{
$user = User::find($id);
// user/createOrUpdate.blade.php view
return View::make('user.createOrUpdate')->with('user', $user);
}
Add/edit in view with the help of user model
#if(isset($user))
{{ Form::model($user, ['route' => ['updateroute', $user->id], 'method' => 'patch']) }}
#else
{{ Form::open(['route' => 'createroute']) }}
#endif
{{ Form::text('fieldname1', Input::old('fieldname1')) }}
{{ Form::text('fieldname2', Input::old('fieldname2')) }}
{{ Form::submit('Save', ['name' => 'submit']) }}
{{ Form::close() }}

// To create a new user in controller
public function create()
{
// user/createOrUpdate.blade.php view
return view('user.createOrUpdate')->with([
'view_type' => 'create',
]);
}
// To update an existing user
public function edit($id)
{
$user = User::find($id);
// user/createOrUpdate.blade.php view
return view('user.createOrUpdate')->with([
'view_type' => 'edit',
'user' => $user
]);
}
<form action="{{ ( $view_type == 'edit' ? route('example', $id) : route('control.mentors.store')) }}" role="form" method="post" name="frmDetail">

Related

search by multiple values using checkbox in laravel

I have job_sector table in which sector_id and job_id fields are there. I just want to search job_id by the sectors which I have selected through checkbox. One may select multiple sectors.
My model :
public function scopeSelectedOptions($query, $input = [])
{
if(!empty($input)) {
if(array_key_exists('sector_id', $input)) {
$query->whereHas('sector_id', function($q) use ($input) {
return $q->whereIn('sector_id', $input['sector_id']);
});
}
}
return $query;
}
Controller :
public function jobsFilter(Request $request)
{
$jobs = JobSector::SelectedOptions(request()->all())->get();
return view('front.pages.job.jobfilter')->with(['title'=>'Job Filter', 'jobs' => $jobs]);
}
Form from where I am selecting multiple sectors :
<form action="{{ route('job.jobfilter') }}" method="GET" class="mb-4">
{{csrf_field()}}
#foreach(get_sectors() as $k=>$s)
<input type="checkbox" name="input[]" value="{{ $k }}">{{ $k }}<br>
#endforeach
<input type="submit" value="Search" />
</form>
Query showing the output :
#foreach($jobs as $c)
{{ $c->job_id }} <br>
#endforeach
It shows me all the job_id in the table.
Please help me out,
You are giving the wrong array to your scope
it would look like this :
['input' => ['12' => true]]
try this
<form action="{{ route('job.jobfilter') }}" method="GET" class="mb-4">
{{csrf_field()}}
#foreach(get_sectors() as $k=>$s)
<input type="checkbox" name="sector_id[{{ $k }}]">{{ $k }}<br>
#endforeach
<input type="submit" value="Search" />
</form>
public function jobsFilter(Request $request)
{
$jobs = JobSector::whereIn('sector_id', array_keys(request()->sector_id))->get();
return view('front.pages.job.jobfilter')->with(['title'=>'Job Filter', 'jobs' => $jobs]);
}
(I just ignore your scope to be more readable)

Edit two unique value with laravel

I have a problem with my Laravel 5.8 project. I want to edit one of two field that both have unique value.
Blade:
#extends('layouts.master')
#section('content')
<h1>CHANGE SURGICAL DIVISION</h1>
<a href="/surgical-div">
<button type="button" class="btn btn-primary btn-sm">BACK</button><br>
</a>
#if (session('mess'))
<div class="alert alert-success">
{{ session('mess')}}
</div>
#endif
<form method="POST" action="/surgical-div/{{ $surgicaldivs->id_surgical_div }}">
#method('patch')
#csrf
<div class="form-group">
<label for="name_surgical_div">Surgical Division Name: </label>
<input type="text" value="{{ $surgicaldivs->name_surgical_div }}"
class="form-control #error('name_surgical_div') is-invalid #enderror" id="name_surgical_div" name="name_surgical_div"
placeholder="Insert The Surgical Division">
#error('name_surgical_div')
<div class="invalid-feedback">
{{ $message }}
</div>
#enderror
</div>
<div class="form-group">
<label for="initial_surgical_div">Surgical Division Initial : </label>
<input type="text" value="{{ $surgicaldivs->initial_surgical_div }}"
class="form-control #error('initial_surgical_div') is-invalid #enderror" id="initial_surgical_div" name="initial_surgical_div"
placeholder="Insert Surgical Division Initial">
#error('initial_surgical_div')
<div class="invalid-feedback">
{{ $message }}
</div>
#enderror
</div>
<button type="submit" class="btn btn-success btn-sm">Save</button>
</form>
#endsection
Controller:
public function edit($id)
{
$surgicaldivs = SurgicalDiv::withTrashed()->find($id);
return view('pages.surgical_div.surgical_div_edit', compact('surgicaldivs'));
}
Model:
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class SurgicalDiv extends Model
{
//Table Name
protected $table = 'surgical_div';
// Primary Key
protected $primaryKey = 'id_surgical_div';
//Soft Deletes
use SoftDeletes;
//Fillable Field
protected $fillable = ['name_surgical_div', 'initial_surgical_div'];
}
This is the update in the controller that i've tried :
public function update(Request $request, SurgicalDiv $SurgicalDiv)
{
$request->validate([
'name_surgical_div' => 'required|unique:surgical_div,name_surgical_div',
'initial_surgical_div' => 'required|unique:surgical_div,initial_surgical_div'
]);
SurgicalDiv::withTrashed()->where('id_surgical_div',$id)
->update([
'name_surgical_div' => $request->name_surgical_div,
'initial_surgical_div' => $request->initial_surgical_div
]);
return redirect('/surgical-div/'.$id.'/edit')->with('mess',' Surgical Division Change Success !');
}
I don't know what to put on the update function in the controller. I want to update one or even both of the field from my blade.
Try this
public function update(Request $request, SurgicalDiv $SurgicalDiv)
{
$request->validate([
'name_surgical_div' => 'required|unique:surgical_div,name_surgical_div,'.$id,
'initial_surgical_div' => 'required|unique:surgical_div,initial_surgical_div,'.$id
]);
SurgicalDiv::withTrashed()->where('id_surgical_div',$id)
->update([
'name_surgical_div' => $request->name_surgical_div,
'initial_surgical_div' => $request->initial_surgical_div
]);
return redirect('/surgical-div/'.$id.'/edit')->with('mess',' Surgical Division Change Success !');
}
This will check the table for same entries except the row with the $id. This way you can check if there are any other rows with same values in the two columns.

Undefined variable: posts when passing parameter from controller to view

I'm trying to create a search function in Laravel and its returning me with "undefined variable: posts" when I do foreach on my view.
My code:
Post Model
class Post extends Model {
protected $fillable = [
'creator',
'post_url',
'books',
'likes',
'created_at'
];
public function user() { return $this->belongsTo(User::class); }
}
Homeview:
<form action="{{ url('/search') }}" method="get">
<input type="text" class="search-text form-control form-control-lg" name="q" placeholder="Search" required>
</form>
Controller:
public function search($keyword)
{
$result = Post::where('books', 'LIKE', "'%' . $keyword . '%'")->get();
return view('/search', ['posts' => $result]);
}
Route:
Route::get('/search/{keyword}', 'SearchController#search');
Searchview:
#foreach($posts as $post)
<div class="post">{{ $post->id }}</div>
#endforeach
What am I doing wrong here?
This might help you out.
Homeview.blade.php
<form action="/search" method="POST">
#csrf // include your csrf token
<input type="text" class="search-text form-control form-control-lg" id="q" name="q" placeholder="Search" required>
</form>
Searchview.blade.php
<!-- or did you return a collection? -->
#if( $posts->count() > 1 )
<!-- then loop through the posts -->
#foreach( $posts as $post )
<div class="post"> {{ $post->id }} </div>
#endforeach
#else
#if( !empty($posts) )
<div class="post"> {{ $post->id }} </div>
#endif
#endif
Routes/web.php
Route::post('/search', 'PostsController#show')->name('posts.show');
PostsController
use App\Post;
public function show( Request $request )
{
$result = Post::where("books", "LIKE", "%{$request->input('q')}%")->get();
// Uncomment the following line to see if you are returning any data
// dd($result);
// Did you return any results?
return view('searchview', ['posts' => $result]);
}
The reason it wasn't working,
Route::get('/search/{keyword}', 'SearchController#search');
In your route file you were looking for a {keyword} that was never passed by the form. Your form action is action="{{ url('/search') }}". A get variable will not be picked up by a route and if it was you called the input 'q' anyway.
So then in your controller you were looking for the keyword being passed that is never passed in.
public function search($keyword)
Instead the correct thing to do is pass in the Request object like so
public function search(Request $request)
Then use $request->input('q') to retrieve the passed value through your form.
In your example $keyword would always have been blank.
Corrected code
Homeview:
<form action="{{ url('/search') }}" method="get">
<input type="text" class="search-text form-control form-control-lg" name="q" placeholder="Search" required>
</form>
Controller:
public function search(Request $request)
{
$result = Post::where('books', 'LIKE', "%{$request->input('q')}%")->get();
return view('/search', ['posts' => $result]);
}
Route:
Route::get('/search', 'SearchController#search');
Searchview:
#foreach($posts as $post)
<div class="post">{{ $post->id }}</div>
#endforeach
try:
return view('/search')->with('posts', $result);
Or even better with dinamic vars.
return view('/search')->withPosts($result);

Laravel - How to handle errors on PUT form?

I am working with laravel 5.2 and want to validate some data in an edit form. I goal should be to display the errors and keep the wrong data in the input fields.
My issue is that the input is validated by ContentRequest and the FormRequest returns
$this->redirector->to($this->getRedirectUrl())
->withInput($this->except($this->dontFlash))
->withErrors($errors, $this->errorBag);
which is fine so far. Next step the edit action in the controller is called and all parameters are overwritten.
What I have currently done:
ContentController:
public function edit($id)
{
$content = Content::find($id);
return view('contents.edit', ['content' => $content]);
}
public function update(ContentRequest $request, $id)
{
$content = Content::find($id);
foreach (array_keys(array_except($this->fields, ['content'])) as $field) {
$content->$field = $request->get($field);
}
$content->save();
return redirect(URL::route('manage.contents.edit', array('content' => $content->id)))
->withSuccess("Changes saved.");
}
ContentRequest:
class ContentRequest extends Request
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'title' => 'required|min:3',
'body' => 'required|min:3'
];
}
}
How can I fix this? The form looks like this:
<form action="{!! URL::route('manage.contents.update', array('content' => $content->slug)) !!}"
id="site-form" class="form-horizontal" method="POST">
{!! method_field('PUT') !!}
{!! csrf_field() !!}
<div class="form-group {{ $errors->has('title') ? 'has-error' : '' }}">
<label for="title" class="col-sm-2 control-label">Title</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="title" id="title" placeholder="Title"
value="{{ $content->title }}">
#if ($errors->has('title'))
<span class="help-block">
<strong>{{ $errors->first('title') }}</strong>
</span>
#endif
</div>
</div>
</form>
Try something like the following:
<input
type="text"
class="form-control"
name="title"
id="title"
placeholder="Title"
value="{{ old('title', $content->title) }}" />
Note the value attribute. Also check the documentation and find Retrieving Old Data.

Laravel 4 - Update many to many

I am currently trying to amend an update page which features a many to many relationship. It updates to my database perfectly, however all I'm trying to achieve now is to actually show the already selected items in my multiple select list in my view.
It currently just shows the entire list of oilgas jobs, just not the currently selected ones which should come from the query in some way.
So, it currently looks like this:
I need it to look like this, if Instrument Technician was previously chosen.
The associated files are as follows:
MODELS
OilGasJob.php
<?php
class OilGasJob extends \Eloquent {
protected $table = 'oilgasjobs';
public function industryjobs()
{
return $this->belongsToMany('IndustryJob');
}
}
IndustryJob.php
<?php
class IndustryJob extends \Eloquent {
protected $table = 'industryjobs';
public function oilgasjobs()
{
return $this->belongsToMany('OilGasJob');
}
}
CONTROLLER (CREATE PAGE AND STORE)
public function edit($id)
{
$industryjob = IndustryJob::find($id);
if(is_null($id))
{
return Redirect::to('/admin/industry-jobs')->with('message', 'This division job is not valid');
}
View::share('page_title', 'Edit Division Job');
return View::make('admin/industry-jobs/edit')->with('industryjob',$industryjob);
}
public function update($id)
{
$rules = array(
'job_title' => 'Required|Min:3|Max:80'
);
$validation = Validator::make(Input::all(), $rules);
If ($validation->fails())
{
return Redirect::back()->withErrors($validation);
} else {
$industryjob = IndustryJob::find($id);
if(is_null($id))
{
return Redirect::to('/admin/industry-jobs')->with('message', 'This divison job is not valid');
}
View::share('page_title', 'Edit Division Job');
$industryjob->job_title = Input::get('job_title');
$industryjob->slug = Str::slug(Input::get('job_title'));
$industryjob->job_description = Input::get('job_description');
$industryjob->job_qualifications = Input::get('job_qualifications');
$industryjob->save();
$industryjob->oilgasjobs()->sync(Input::get('oilgasjobs'));
return Redirect::to('/admin/industry-jobs')->with('message', 'Division Job updated successfully');
}
}
VIEW
{{ Form::open(array('url' => URL::to('admin/industry-jobs/edit/'.$industryjob->id), 'class'=>'form-horizontal', 'method' => 'POST')) }}
<div class="form-group">
<label class="col-md-2 control-label" for="industry_name">Job Title (*)</label>
<div class="col-md-10">
<input class="form-control" type="text" name="job_title" id="job_title" value="{{ $industryjob->job_title }}" />
</div>
</div>
<!-- Industry Type -->
<div class="form-group">
<label class="col-md-2 control-label" for="body">Related Jobs in Oil & Gas</label>
<div class="col-md-10">
<select name="oilgasjobs[]" id="oilgasjobs[]" size="6" class="form-control" multiple>
#foreach(OilGasJob::orderBy('job_title', 'ASC')->get() as $oilgasjob)
<option value="{{ $oilgasjob->id }}" >{{ $oilgasjob->job_title }}</option>
#endforeach
</select>
</div>
</div>
<!-- ./ Industry Type -->
<!-- Form Actions -->
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="reset" class="btn btn-default">Reset</button>
<button type="submit" class="btn btn-success">Update Job</button>
</div>
</div>
<!-- ./ form actions -->
{{ Form::close() }}
In edit method add this code:
// ...
$linkedOilgasjob = DB::table('oilgasjob_industryjob')->lists('oilgasjob_id');
return View::make('admin/industry-jobs/edit'
,compact('industryjob')
,compact('linkedOilgasjob'));
Then in your view
<option value="{{ $oilgasjob->id }}" {{ in_array($oilgasjob->id,linkedOilgasjob) ? "selected='selected'" : "" }} >
{{ $oilgasjob->job_title }}
</option>
CONTROLLER
public function edit($id)
{
$data['industryjob'] = IndustryJob::find($id);
$data['oilgasjobs'] = DB::table('industry_job_oil_gas_job')->where('industry_job_id','=',$id)->lists('oil_gas_job_id');
if(is_null($id))
{
return Redirect::to('/admin/industry-jobs')->with('message', 'This division job is not valid');
}
View::share('page_title', 'Edit Division Job');
return View::make('admin/industry-jobs/edit', $data);
}
VIEW
<select name="oilgasjobs[]" id="oilgasjobs[]" size="6" class="form-control" multiple>
#foreach(OilGasJob::orderBy('job_title', 'ASC')->get() as $oilgasjob)
<?php
$selected = "";
if(in_array($oilgasjob->id, $oilgasjobs))
$selected = "selected";
?>
<option value="{{ $oilgasjob->id }}" <?php echo $selected; ?>>{{ $oilgasjob->job_title }}</option>
#endforeach
</select>

Resources