Display primary video for specific ad/property in Laravel - php

I am working on a project for ads/properties in Laravel. I have gallery of multiple videos for each individual ad. I want to be able to select one of those videos with radio button and make it primary video for that ad (show that particular video next to ad). I have has many relationship between property and video. I am trying to update my is_main_video column to be 1 if it is main or 0 if it isn't and then display that video if it is 1 in my view. I am having trouble to write that method in my controller I get success message but my is_main_video column remains null. Any help is appreciated. Here are my tables and code.
properties (id, title, location, price)
videos (id, filename_video, model_id, is_main_video)
In videos table model_id column is foreign key that connects to properties table.
PropertyController.php
public function update(StorePropertyInfo $request, Property $property, Video $video)
{
$videoExtensions = ['mp4', '3gp', 'wmv', 'flv', 'avi'];
$image_arr = array_filter(explode(',', $request->image), 'strlen');
foreach ($image_arr as $key => $value) {
$file = explode('.', $value);
ext = end($file);
if (in_array($ext, $videoExtensions)) {
$query = Property::query();
if ($request->has('radio')) {
$request->get('radio');
}
if ($request->radio) {
$query->whereHas('videos', function ($query) use ($request) {
$query->where('is_main_video', 'like', '%' . $request->radio . '%');
});
}
$data = $query;
$video->where('filename_video', $value)
->update([
'model_id' => $property->id,
'is_main_video' => $data
]);
};
$request->validated();
return redirect()
->back()
->with('message', 'Property information updated');
}
}
edit.blade.php
<input type="hidden" id="hideninput" data-src="property/{{$property->id}}/gallery"value="{{old('video',$video)}}" name="video">
#if (old('video', $video))
#foreach (array_filter(explode(',',old('video', $video)), 'strlen') as $key =>$value)
<div id="{{'div_video_'.$key}}" class="col-md-3" style="padding: 15px;">
<input type="radio" name="radio" value="radio">Make main
<button data="{{$key}}" type="button" class="closebuttonvideo">
<span aria-hidden="true">×</span>
</button>
<video name="video" id="{{'video_'.$key}}" data={{$value}} src="/storage/property/{{$property->id}}/gallery/{{$value}}" class="video-js vjs-default-skin" controls preload="auto" data-setup='{"inactivityTimeout": 0}' width="180" height="180"></video>
</div>
#endforeach
#endif
videos table migration
public function up()
{
Schema::table('videos', function (Blueprint $table) {
$table->boolean('is_main_video')->nullable()->default(null);
$table->unique(['model_id', 'is_main_video']);
});
}
Property.php
protected $appends = ['is_main_video'];
public function videos()
{
return $this->hasMany(Video::class, 'model_id');
}
Video.php
public function properties()
{
return $this->belongsTo(Property::class);
}

I would do a partial rewrite, something like this:
PropertyController.php in edit(); Retrieving a property with attached videos.
return view('edit', [
'property' => Property::with('videos')->find(1),
]);
edit.blade.php
#foreach($property->videos as $video)
<input type="radio" name="main_video" value="{{ $video->id }}">Video {{ $video->id }}<br>
#endforeach
PropertyController.php in update(); Toggle the is_main_video attribute of each video of the property.
foreach ($property->videos as $video) {
$video->is_main_video = ($video->id == $request->input('main_video'));
$video->save();
}

Related

how to show photos on my .blade view page from mysql database specific to id

I am building a classified website and I am trying to set it up to show one photo from the database on the main page, that same photo on a category page, but when you view the full page of the item for sale I want to show all of the photos in that section.
Like how ebay shows one photo for the ad but when you click the ad it shows several photos.
I have used 'strtok' to show the single photo in my main page and category page but now I don't know how to setup the view page to show all the photos for that item.
here is how I am saving the images when the listing is posted.
public function postHobbies(Request $request)
{
$this->validate($request, [
'photos' => 'required',
'Photos.*' => 'image|mimes:jpg, png, jpeg, gif, aae, heif, svg|max:2048'
]);
$ads = new Listings;
$images = $request->file('photos');
$count = 0;
if ($request->file('photos')) {
foreach ($images as $item) {
if ($count < 6) {
$var = date_create();
$date = date_format($var, 'Ymd');
$imageName = $date . '_' . $item->getClientOriginalName();
$item->move(public_path() . '/uploads/', $imageName);
$url = URL::to("/") . '/uploads/' . $imageName;
$arr[] = $url;
$count++;
}
}
$image = implode(",", $arr);
$ads->photos = $image;
$ads->save();
return redirect('/')->with('info', 'Listing published successfully');
}
}
here is my controller for the page I am trying to post all of the photos on
public function view(Request $request, $id)
{
$ads = DB::table('listings')
->select('listings.id', 'photos', 'description', 'year', 'make', 'model', 'price', 'city', 'state', 'email')
->where(['id' => $id])
->get();
$output = '';
if ($ads->count() > 0) {
return view('users.posted.postedads', ['id' => $id, 'ads' => $ads]);
}
}
And finally here is how I am currently passing it which is just showing me the single photo since I am still using the 'strtok' to make sure it works. So i assume i need to change this function i just don't know what to use or how to use it.
<div class="row">
#if(count($ads)>0)
#foreach($ads as $row)
<div class="col-md-12">
<div class="productCard">
<img style="width:100%; height:100%;" src="<?php echo strtok($row->photos, ',')?>" />
</div>
</div>
#endforeach
#else
#endif
First of all, you need to save many images, you are saving only one image now.
It is recommended to make another model for images (for example Image), and make one to many or many to many relationships between Listings(it is better to user singular name for models).
Then, in your view method you need to retrieve related models with Listings->with('images') and in your view file, you need add another foreach loop where you want to display images.
View code would be something like this:
<div class="row">
#if(count($ads)>0)
#foreach($ads as $row)
<div class="col-md-12">
<div class="productCard">
#foreach($row->images as $image)
<img style="width:100%; height:100%;" src="{{ $image->url }}" />
#endforeach
</div>
</div>
#endforeach
#else
#endif
Note I used {{ }} Laravel Blade directive instead of <?php echo, you should too

How to associate files to post with Laravel 5.6

I am using Laravel for my web app and I want to associate files to my posts in indepent way with his own form, but I have some problems
My routes (I am using a auth control package, but actually I am admin):
Route::post('file', 'fileController#store')->name('file.store')
->middleware('permission:file.create');
Route::get('file', 'fileController#index')->name('file.index')
->middleware('permission:file.index');
Route::get('file/create/', 'fileController#create')->name('file.create')
->middleware('permission:file.create');
Route::put('file/{id}', 'fileController#update')->name('file.update')
->middleware('permission:file.edit');
Route::get('file/{id}', 'fileController#show')->name('file.show')
->middleware('permission:file.show');
Route::delete('file/{id}', 'fileController#destroy')->name('file.destroy')
->middleware('permission:file.destroy');
Route::get('file/{id}/edit', 'fileController#edit')->name('file.edit')
->middleware('permission:file.edit');
Route::get('download/{filename}', 'fileController#download')->name('file.download')
->middleware('permission:file.download');
My migration:
Schema::create('files', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('files_id')->unsigned();
$table->string('filenames');
$table->integer('fileable_id')->unsigned();
$table->string('fileable_type');
$table->timestamps();
});
My File Model:
class File extends Model
{
protected $fillable = [
'filenames', 'project_id'
];
public function user()
{
return $this->belongsTo(User::class);
}
My Project Model:
public function files()
{
return $this->morphMany(File::class, 'fileable')->whereNull('files_id');
}
My Controller to store:
class FileController extends Controller
{
public function store(Request $request)
{
$this->validate($request, [
'filenames' => 'required',
'project_id' => 'required',
// 'filenames.*' => 'mimes:doc,pdf,docx,zip'
]);
if($request->hasfile('filenames'))
{
foreach($request->file('filenames') as $file)
{
$name=$file->getClientOriginalName();
$file->move(public_path().'/files/', $name);
$data[] = $name;
}
}
$file= new File();
$file->filenames = $request->get('filenames');
$file->filenames= $name;
$file->user()->associate($request->user());
$project = Project::findOrFail($request->get('project_id'));
$project->files()->save($file);
$file->save();
return back();
}
public function download( $filename = '' ) {
// Check if file exists in storage directory
$file_path = public_path() . '/files/' . $filename;
if ( file_exists( $file_path ) ) {
// Send Download
return \Response::download( $file_path, $filename );
} else {
return back()->with('info', 'Archivo no existe en el servidor');
}
}
The Form in blade:
<form method="post" action="{{ route('file.store') }}" enctype="multipart/form-data">
<div class="input-group hdtuto control-group lst increment" >
<input type="file" name="filenames[]" class="myfrm form-control">
<input type="hidden" name="project_id" value="{{ $project->id }}" />
<div class="input-group-btn">
<button class="btn btn-success" type="button"><i class="fldemo glyphicon glyphicon-plus"></i>Add</button>
</div>
</div>
<button type="submit" class="btn btn-success" style="margin-top:10px">Submit</button>
</form>
Foreach to download files:
#foreach($project->files as $file)
<li>{{ $file->user->name }}: <a href="{{ url('/download/')}}/{{$file->filenames}}" download> {{$file->filenames}}</a></li>
#endforeach
I send files from Project Controll
The reason you are getting the first error message is because the Project with the id you get from Request is not found in the Database and returns null instead of an object. That would mean you are indeed calling files() method on null. To resolve this there are multiple steps.
1.) Make sure project_id is inside the Request at all times:
$this->validate($request, [
'filenames' => 'required',
'project_id' => 'required',
// 'filenames.*' => 'mimes:doc,pdf,docx,zip'
]);
2.) Make sure to check for project if it exists after retrieving it from database, this can be done in two ways.
a) You can either find the project or throw an Exception if it's not found:
$project = Project::findOrFail($request->get('project_id');`
b) You can check with a simple if statement if it does not exist and do something
$project = Project::find($request->get('project_id');
if (!$project) {
// Project not found in database
// Handle it
}

Show in the table the search results when the user clicks in the "Search" button

I have this 2 methods in the ParticipantController. The index() show some info of all registrations in a conference. Then the search() is for a search form in the view, to show only in the table the results where the user that did the registration has the name like the name introduced by the user in the search form:
class ParticipantController extends Controller
{
public function index($id){
$conference = Conference::find($id);
$conference->load('registrations.participants.answers.question');
return view('participants.index')->with('conference', $conference);
}
public function search($id, Request $request)
{
$name = $request->get('participant');
$conference = Conference::findOrFail($id);
$searchInfo = $conference->load([
'registrations.participants' => function ($query) use ($name) {
return $query->where('name', 'like', '%' . $name . '%');
},
'registrations.participants.answers.question'
]);
return view('participants.index', compact('conference'));
}
}
The routes that I have for this methods:
Route::get('conference/edit/{id}/participants', [ 'uses' => 'ParticipantController#index', 'as' => 'participants.index']);
Route::get('conference/edit/{id}/participants/search', [
'uses' => 'ParticipantController#search',
'as' => 'participants.search'
]);
My doubt is how to show the search results in the view after the user enter some data in the search form and click "Search". When the user acesses the participants/index.blade.php all registrations are already listed in a table with the foreach below using the code in the index() method:
#foreach($conference->registrations as $registration)
<tr>
<td>{{$registration->customer->name}} {{$registration->customer->surname}}</td>
<td>{{ $registration->status === 'C' ? 'Complete' : 'Incomplete' }}</td>
<td><a data-regid="{{$registration->id}}"> More details</a></td>
</tr>
#endforeach
And its working fine the table show the details of all registrations like:
User that did the registration Quantity Status Details
Jake K 2 Complete Show
...
But in this view there is also the search form, my doubt is how to show in the table the search results when the user introduces a name in the search form and click "Search".
HTML of the search form in the view:
<form action="{{ route('participants.search', ['id' => $conference->id] )}}" method="get">
<div class="form-row">
<div class="form-group col col-md-6">
<label for="participant">Search</label>
<div class="input-group">
<input type='text' name="participant" class="form-control" placeholder="Name" />
</div>
</div>
</div>
</form>
Change you search action like this
public function search($id, Request $request)
{
$name = $request->get('participant');
$conference = Conference::with(['registrations.participants' => function() ($query) use ($name){
return $query->where('name', 'like', '%' . $name . '%');
},'registrations.participants.answers.question'])->findOrFail($id);
return view('participants.index', compact('conference'));
}
Now if you look carefully both index and search has the same return type conference only the difference is in search we have filtered participants.
OR
you can just add the search functionality in index action too
public function index($id, Request $request){
$name = $request->get('participant');
if($name){
$conference = Conference::with(['registrations.participants' => function() ($query) use ($name){
return $query->where('name', 'like', '%' . $name . '%');
},'registrations.participants.answers.question'])->findOrFail($id);
}else{
$conference = Conference::with('registrations.participants.answers.question')->findOrFail($id);
}
return view('participants.index')->with('conference', $conference);
}
You can use datatables
Link : https://github.com/yajra/laravel-datatables
Check . this will solve your problem .
This would help you with what you need - https://datatables.net/examples/styling/bootstrap

Laravel advanced search query fix

I have a search form with multiple input and select boxes I need help to get if conditions in my query in order to each part works separately and all at once.
here is my blade codes:
<form action="{{route('advancesearch')}}" method="post">
{{csrf_field()}}
<div class="sidebar-title">
<span>Advanced Search</span>
<i class="fa fa-caret-down show_sidebar_content" aria-hidden="true"></i>
</div>
<!-- ./sidebar-title -->
<div id="tags-filter-content" class="sidebar-content">
<div class="filter-tag-group">
#foreach($options as $option)
<div class="tag-group">
<p class="title">
<span class="filter-title show_filter_content">{{$option->title}} <span class="pull-right"><i class="fa fa-minus"></i></span></span>
</p>
<div class="filter-content">
<div class="checkbox">
#foreach($option->suboptions as $suboption)
<label for="suboptions">
<input name="suboptions[]" type="checkbox" value="{{$suboption->id}}">
{{ucfirst($suboption->title)}}
</label>
#endforeach
</div>
</div>
</div>
#endforeach
<!-- ./tag-group -->
<div class="tag-group">
<p class="title">
<span class="filter-title show_filter_content">Brand <span class="pull-right"><i class="fa fa-minus"></i></span></span>
</p>
<div class="filter-content">
<div class="checkbox">
#foreach($brands as $brand)
<label for="brands">
<input name="brands[]" type="checkbox" value="{{$brand->id}}">
{{$brand->title}}
</label>
#endforeach
</div>
</div>
</div>
<!-- ./tag-group -->
<div class="tag-group">
<p class="title">
<span class="filter-title show_filter_content">Price Range <span class="pull-right"><i class="fa fa-minus"></i></span></span>
</p>
<div class="row filter-content">
<div class="col-md-6">
<div class="form-group">
<label for="min_price" hidden>Min</label>
<input type="text" name="min_price" class="form-control" placeholder="Rp Min">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="max_price" hidden>Max</label>
<input type="text" name="max_price" class="form-control" placeholder="Rp Max">
</div>
</div>
</div>
</div>
<!-- tag-group -->
<div class="text-center mt-20">
<button type="submit" class="btn btn-danger">TERPAKAN</button>
</div>
</div><!-- ./filter-tag-group -->
</div><!-- ./sidebar-content -->
</form>
and this is my route:
Route::post('/advanced-search', 'frontend\SearchController#filter')->name('advancesearch');
finally my function code is:
public function advancedsearch(Request $request) {
$brands = Brand::all(); // uses for other part of the page. (not related to search function)
$options = Option::all(); // uses for other part of the page. (not related to search function)
$suboptions = DB::table('product_suboption'); // where my product_id and subopyion_id saves
//search function
$products = Product::where(function($query){
//getting inputs
$suboptions2 = Input::has('suboptions') ? Input::get('suboptions') : [];
$min_price = Input::has('min_price') ? Input::get('min_price') : null;
$max_price = Input::has('max_price') ? Input::get('max_price') : null;
$brands2 = Input::has('brands') ? Input::get('brands') : [];
//returning results
$query->where('price','>=',$min_price)
->where('price','<=',$max_price);
})->get();
return view('front.advancesearch', compact('products', 'brands', 'options'));
}
My models relations:
product model:
public function options(){
return $this->belongsToMany(Option::class);
}
public function suboptions(){
return $this->belongsToMany(Suboption::class, 'product_suboption', 'product_id', 'suboption_id');
}
public function brand(){
return $this->belongsTo(Brand::class);
}
Option model:
public function suboptions(){
return $this->hasMany(Suboption::class, 'option_id');
}
public function products(){
return $this->belongsToMany(Product::class);
}
Suboption model:
public function option(){
return $this->belongsTo(Option::class, 'option_id');
}
public function products(){
return $this->belongsToMany(Product::class);
}
Brand model:
public function products(){
return $this->hasMany(Product::class);
}
note
My brands search is coming from products table where I have column brand_id for each product.
BUT
My suboptions come from 3rd table named product_suboption (as you see in my models codes) where i save product_id and suboption_id.
This is just to give an idea. You can use a multiple ->where() and eager loading ->with() for your query.
Take a look with this query below:
$products = Product::where('price', '>=', $min_price) // you get the max and min price
->where('id', '<=', $max_price)->select('id')
->with([
"brand" => function ($query) {
$query->whereIn('id', $brand_ids); // [1, 2, 3,...]
},
"specifications" => function ($query) {
$query->where('some_column', '=', 'possible-value'); // single condition
},
"specifications.subspecifications" => function ($query) {
$query->where([
'some_column' => 'possible-value',
'another_column' => 'possible-value'
]); // you can also pass arrays of condition
}
])->get(); // This will return the products with the price set by the user
// Since we're just using ->with(), this will also return those products
// that doesn't match the other criteria specifications) so we
// still need to filter it.
Finally, you can filter the products which matches the specifications,
- the product with an empty specifications means this product does not match the criteria, therefore we'll have to remove it from the collection.
$filtered = $products->filter(function ($product, $key) {
return count($product->brand) > 0 && count($product->specifications) > 0;
// add your other boolean conditions here
});
dd($filtered->toArray()); // your filtered products to return
You can use laravel orWhere and orWhereHas to get results separately and all at once, let's say you do not select min_price and max_price but you have selected brand then all products with this brnad should be return, your query will look like this
$products = Product::orWhere('price','>=',$min_price)
->orWhere('price','<=',$max_price)
->orWhereHas('brand',function($query){
$query->whereIn('id', $brand_ids);
})
->orWhereHas('suboptions',function($query){
$query->whereIn('id', $suboptions_ids);
})
->orWhereHas('subspecifications',function($query){
$query->whereIn('id', $subspecifications_ids);
})->get();
$products will have products collection If any of the condition stated in above query matched.
Hope this helps.
Here's how I'd do it. Note the use of when for simplifying optional where conditions (no need to set variables either), and the closure for constraining both the whereHas and the with (if you want to eager load the relationships).
$products = Product::query()
->when($request->min_price, function ($query, $min_price) {
return $query->where('price', '>=', $min_price);
})
->when($request->max_price, function ($query, $max_price) {
return $query->where('price', '<=', $max_price);
})
->when($request->suboptions, function ($query, $suboptions) {
$suboptionsConstraint = function ($q) use ($suboptions) {
return $q->whereIn('id', $suboptions);
};
return $query->whereHas('suboptions', $suboptionsContraint)
->with(['suboptions' => $suboptionsContraint]);
})
->when($request->brands, function ($query, $brands) {
$brandsConstraint = function ($q) use ($brands) {
return $q->whereIn('id', $brands);
};
return $query->whereHas('brands', $brandsConstraint)
->with(['brands' => $brandsConstraint]);
});
I suggest tu use each separeted and its help you to feature easaly manupulate code
as your typical condition your sub_option come from third table last relation ship is used.
if(count($request['suboptions'])) {
$product->whereHas('options',function($options) use ($request) {
$options->whereHas('suboptions',function($suboption)use($request) {
$suboption->whereIn('id',$request['suboptions']);
});
});
}
for min price max price i assume your price in procuct table
if(! empty($request['min_price'])) {
$product->where('price','>=',$request['min_price']);
}
if(! empty($request['max_price'])) {
$product->where('price','<=',$request['max_price']);
}
for brand as you say brand_id column in product table then
if(count($request['brands'])) {
$product->whereIn('brand_id',$request['brands']);
}
I suggest a different approach.
On your controller, change it to this:
public function advancedsearch(Request $request) {
$suboptions2 = request->suboptions ? request->suboptions : null;
$min_price = request->min_price ? request->min_price : null;
$max_price = request->max_price ? request->max_price : null;
$brands2 = request->brands ? request->brands : null;
$query = Product::select('field_1', 'field_2', 'field_3')
->join('brands as b', 'b.id', '=', 'products.brand_id')
...(others joins);
// here we do the search query
if($suboptions2){
$query->where('suboptions_field', '=', $suboptions);
}
if($min_price && $max_price){
$query->where(function($q2) {
$q2->where('price', '>=', $min_price)
->where('price', '<=', $max_price)
});
}
if($brands2){
$query->where('products.brand_id', '=', $brands2);
}
// others queries
// finish it with this
$query->get();
return view('front.advancesearch', compact('products', 'brands', 'options'));
I find doing it this way is very useful because it can be really easy to implement additional queries.
This is the method I use to search using laravel eloquent with multiple input:
$input = Input::all(); //group all the inputs into single array
$product = Product::with('options','suboptions','brand');
//looping through your input to filter your product result
foreach ($input as $key => $value)
{
if ($value!='') {
if ($key == "max_price")
$product = $product->where('price','<=', $value);
elseif ($key == "min_price")
$product = $product->where('price','>=', $value);
elseif ($key == "brands")
$product = $product->whereIn('brand_id', $value); //assuming that your Input::get('brands') is in array format
elseif ($key == "suboptions")
$product = $product->whereIn('suboption_id', $value);
}
}
$product = $product->get();
The method above will return all products if no input is submitted, and will filter the result based on the input if available, on top of this it's also a good practice to sanitize your inputs with validations before proceeding with the query
SOLVED
After weeks of playing with codes finally I came to the right results for myself (in my case it works this way for others maybe works with other suggested answers)
public function advancedsearch(Request $request) {
$options = Option::all();
$brands = Brand::all();
$brandss = Input::has('brands') ? Input::get('brands') : [];
$suboption = Input::has('suboptions') ? (int)Input::get('suboptions') : [];
$min_price = Input::has('min_price') ? (int)Input::get('min_price') : null;
$max_price = Input::has('max_price') ? (int)Input::get('max_price') : null;
//codes
if(count($request['suboptions'])){
$products = DB::table('products')
->join('product_suboption', function ($join) {
$suboption = Input::has('suboptions') ? Input::get('suboptions') : [];
$join->on('products.id', '=', 'product_suboption.product_id')
->where('product_suboption.suboption_id', '=', $suboption);
})
->paginate(12);
}
elseif(count($request['brands'])){
$products = DB::table('products')
->whereIn('products.brand_id', $brandss)
->paginate(12);
}
elseif(count($request['min_price']) && count($request['max_price'])){
$products = DB::table('products')
->whereBetween('price', [$min_price, $max_price])
->paginate(12);
}
return view('front.advancesearch', compact('products', 'brands', 'options'));
}
NOTE: most of my pricing issues solved with (int) as you see in my codes (int)Input::get('min_price') and
(int)Input::get('max_price').
Special thanks to Ravindra Bhanderi for his count($request[''] suggestion.
it is very simple to make dynamic search by using treats we can use this for all models I made this dynamic as possible
This is a trait that can be used by any models
This function will remove code repetitions into your project
public function scopeSearch($query, $keyword, $columns = [], $relativeTables = [])
{
if (empty($columns)) {
$columns = array_except(
Schema::getColumnListing($this->table), $this->guarded
);
}
$query->where(function ($query) use ($keyword, $columns) {
foreach ($columns as $key => $column) {
$clause = $key == 0 ? 'where' : 'orWhere';
$query->$clause($column, "LIKE", "%$keyword%");
if (!empty($relativeTables)) {
$this->filterByRelationship($query, $keyword, $relativeTables);
}
}
});
return $query;
}
Filter into relationship also
private function filterByRelationship($query, $keyword, $relativeTables)
{
foreach ($relativeTables as $relationship => $relativeColumns) {
$query->orWhereHas($relationship, function($relationQuery) use ($keyword, $relativeColumns) {
foreach ($relativeColumns as $key => $column) {
$clause = $key == 0 ? 'where' : 'orWhere';
$relationQuery->$clause($column, "LIKE", "%$keyword%");
}
});
}
return $query;
}

Updating database with laravel

Let me explain situation, person is searching through skills and when clicked displays list of handymans with that skill, when user clicks on one of them, full details are displayed. user then clicks assign job link and is taken to a page with jobs along with checkbox and when desired job is chosen, and submit button clicked, I want a database to update "job_id" value in "handymen" database. How could that be done?
#extends('layouts.master')
#section('title', 'Assign Job')
#section('content')
#section('content')
<form action="{{url('assignjob')}}" method="POST">
{{ csrf_field() }}
#foreach ($jobs as $job)
<div>
<label>{{$job->name}}</label>
<input type='checkbox' value='{{$job->id}}' name='jobs[]'/>
</div>
#endforeach
<input type="submit" name="submitBtn" value="Assign Job">
</form>
#endsection
function search()
{
$skills = Skill::all();
return view('layouts/search',['skills' => $skills]);
}
function details($skillId)
{
$skill = Skill::find($skillId);
$handymen = $skill->handymen;
return view('layouts/details', ['skill' => $skill,'handymen' => $handymen]);
}
function assignJob($handymanId)
{
$assignJob = Hadnyman::find($handymanId);
$jobs = Job::all();
return view('layouts/assignjob',['jobs' => $jobs]);
}
function jobassign(Request $request)
{
return redirect('assignjob');
}
function skilledHandyman($handymanId)
{
$skilledHandyman = Handyman::find($handymanId);
return view('layouts/skilledHandyman', ['skilledHandyman' => $skilledHandyman]);
}
If a specific code is needed, please let me know
You should look at Eloquent Relationship.
Handymen has many Job
class Handymen extends Model {
...
public function jobs() {
return $this->hasMany(App\Job::class);
}
}
In your controller
function assignJob(Request $request, $id)
{
$handymen = Handyman::findOrFail($id);
// $request->get('jobs') = [1, 6, 7, etc...]
$handymen->saveMany($request->get('jobs'));
return ...;
}

Categories