How do I add a link to the drop down select option? - laravel

This is an image of my drop down select showing islands e.g Maiana as parent and culprits as child e.g Batiboa Kumeto etcI just wondering to know how to add a link in the select option and to pass the id to another form ?.
I tried to create a drop down shown in the image above
Maiana
- Koriaue Miruango
- Batiboa Kumeto
Abaiang
- Erenawa Aeete
but what I can not achieve is to add a link
to Koriaue Miruango, - Batiboa Kumeto under Maiana Island, and the rest. Once one of the name e.g Batiboa Kumeto is clicked an id is passed to load another form.
appreciate your help
My Island Model
<?php
namespace App\Model\Enforcement;
use Illuminate\Database\Eloquent\Model;
class Island extends Model
{
protected $table = 'islands';
protected $fillable = ['island_name'];
public function culprits(){
return $this->hasMany(Culprit::class, 'island_id');
}
}
My Culprit Model
<?php
namespace App\Model\Enforcement;
use Illuminate\Database\Eloquent\Model;
class Culprit extends Model
{
protected $table = 'culprits';
protected $fillable = ['island_id','first_name','last_name','age','home_island'];
public function island(){
return $this->belongsTo(Island::class, 'island_id');
}
public function crimes(){
return $this->hasMany(Crime::class);
}
}
My Controller
<?php
namespace App\Http\Controllers\Frontend\Enforcement;
use App\Model\Enforcement\Culprit;
use App\Model\Enforcement\Island;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class TestController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$islands = Island::with(['culprits'])->get();
// $culprits = Culprit::get();
// dd($islands, $culprits);
return view('backend.enforcement.admin.tests.show',compact('islands','culprits'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create($id)
{
$culprit = Culprit::findOrFail($id);
$offences = Offence::pluck('name','id')->all();
$fishedareas = Fishedarea::pluck('fishedarea_name','id')->all();
return view('backend.enforcement.admin.tests.create',compact('culprit','offences','fishedareas'));
}
My Route
Route::resource('/enforcements/tests', 'Frontend\Enforcement \TestController');
Route::get('/enforcements/tests/{id?}', 'Frontend\Enforcement\TestController#create')->name('tests.create');
My index view
<select data-placeholder="Select island" style="width:350px;" class="chosen-select" tabindex="5">
<option value=""></option>
#foreach ($islands as $island)
<optgroup value="{{$island->id}}" label=" {{$island->island_name}}">
#foreach($island->culprits as $culprit)
<option value = "{{$culprit->id}}"> {{$culprit->first_name}} {{$culprit->last_name}} </option>
</optgroup>
#endforeach
#endforeach
</select>
My Create Form
<div>
{!! Form::open(array('url' => route('tests.store'))) !!}
{!! Form::hidden('id', $culprit->id, old('id'), ['class' => 'form-control']) !!}
{!! Form::label('offence_id','Offence Name')!!}
{!! Form::select('offence_id',['' => 'Choose Offence Type']+ $offences, null, ['class'=>'form-control'])!!}
{!! Form::label('fishedarea_id','Fished Area')!!}
{!! Form::select('fishedarea_id',['' => 'Choose Fished Areas']+ $fishedareas, null, ['class'=>'form-control'])!!}
{!! Form::label('crime_date','Date')!!}
{!! Form::date('crime_date',null,['class'=>'form-control'])!!}
{!! Form::label('remarks','Remarks')!!}
{!! Form::textarea('remarks',null,['class'=>'form-control'])!!}
</div>
<div class="form-group">
<button class="btn btn-primary">Add New</button>
</div>
<div>
{!! Form::close() !!}
</div>

As for know I did some trial and error experiment and come up with something like this that solves my issue. sure there is a better way from your end
<select name="forma" data-placeholder="Select island" style="width:350px;" class="chosen-select" tabindex="5" onchange="location = this.options[this.selectedIndex].value;">
<option value=""></option>
#foreach ($islands as $island)
<optgroup value="{{$island->id}}" label="{{$island->island_name}}">
#foreach($island->culprits as $culprit)
{{--<option value="{{route('tests.create', $culprit->id)}}"> {{$culprit->first_name}} {{$culprit->last_name}}</option>--}}
<option value="{{route('tests.create', $culprit->id)}}">
{{$culprit->first_name}} {{$culprit->last_name}}
</option>
</optgroup>
#endforeach
#endforeach
</select>

Related

How can I save records in attendance table using Laravel?

I am having issue with saving attendance record of student in attendance listings. The frontend part is working well but record saved in backend of attendance table is not shown. How can I save record in backend table of attendance which consists of level_id, teacher_id and student_id
Here is my attendance migrations table
$table->id();
$table->unsignedBigInteger('level_id');
$table->unsignedBigInteger('teacher_id');
$table->unsignedBigInteger('student_id');
$table->foreign('level_id')->references('id')->on('levels');
$table->foreign('teacher_id')->references('id')->on('teachers');
$table->foreign('student_id')->references('id')->on('students');
$table->date('attendance_date');
$table->string('attendance_status');
$table->timestamps();
Here is my students migrations tables
$table->id();
// The Parents table must exist and Must have 'id' as Primary Key
$table->unsignedbiginteger('parent_id');
$table->unsignedbiginteger('level_id');
$table->foreign('parent_id')->references('id')->on('parents')
->onDelete('cascade');
$table->foreign('level_id')->references('id')->on('levels');
$table->string('student_roll_no');
$table->string('student_surname');
$table->string('student_middle_name')->nullable();
$table->string('student_given_name');
$table->string('student_place_of_birth');
$table->date('student_date_of_birth');
$table->string('student_gender');
$table->text('student_home_address');
$table->string('student_suburb')->nullable();
$table->string('student_post_code');
$table->string('student_home_phone')->nullable();
$table->string('student_work_phone')->nullable();
$table->string('student_mobile_phone');
$table->string('student_email')->nullable();
$table->string('student_photo')->nullable();
$table->string('language_spoken_at_home')->nullable();
$table->string('school_name');
$table->string('student_semester')->nullable();
$table->string('school_suburb')->nullable();
$table->text('school_address')->nullable();
$table->string('student_oversea_full_paying')->nullable();
$table->string('emergency_person_one_name')->nullable();
$table->string('emergency_person_one_mobile_number');
$table->string('emergency_person_one_house_number')->nullable();
$table->string('emergency_person_two_name')->nullable();
$table->string('emergency_person_two_mobile_number')->nullable();
$table->string('emergency_person_two_house_number')->nullable();
$table->string('medical_condition')->nullable();
$table->boolean('medical_health_support')->nullable();
$table->boolean('family_court_orders');
$table->string('family_court_file')->nullable();
$table->boolean('authority_to_school_staff');
$table->boolean('authorize_school_staff_to_arrange_medical_treatment');
$table->boolean('authorize_school_staff_administering_medication');
$table->boolean('notify_the_school_absent');
$table->boolean('withdraw_child_from_school');
$table->boolean('authorize_photograph_to_school');
$table->boolean('authorize_child_name_school_newsletter_website');
$table->boolean('authorize_short_local_walks');
$table->boolean('authorize_participate_in_any_incursions');
$table->boolean('information_contained_in_this_form_correct');
$table->boolean('status')->default(1);
$table->timestamps();
Here is my levels tables
$table->bigIncrements('id');
$table->string('level_name');
$table->timestamps();
Here is my Teachers migrations tables
$table->id();
// The Parents table must exist and Must have 'id' as Primary Key
$table->unsignedbiginteger('user_id')->nullable();
$table->foreign('user_id')->references('id')->on('users');
$table->string('teacher_name');
$table->string('teacher_email')->unique();
$table->string('teacher_home_phone')->nullable();
$table->string('teacher_mobile_phone');
$table->string('teacher_work_phone')->nullable();
$table->string('teacher_home_address');
$table->string('teacher_suburb')->nullable();
$table->string('teacher_postcode');
$table->timestamps();
Here is my Attendance Controller
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Levels;
use App\Models\Teacher;
use App\Models\Student;
use App\Models\Attendance;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class AttendanceController extends Controller
{
/**
* Create a new controller instance
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function index($level_id = NULL)
{
$levels = Levels::all();
$students = Student::all();
return view('admin.attendance.list', compact( 'levels', 'students','level_id'));
}
/**
* Perform Actions in attendance.add
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function add()
{
$levels = array();
$students = array();
return view('admin.attendance.add', compact('levels', 'teachers'));
}
/**
* Store values in application dashboard
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function store(Request $request, $level_id)
{
//get form data
$data = $request->all();
//Creeate Student record
$students = Student::all();
$levels = Levels::all();
if($level_id){
$levels = Levels::find($level_id);
if($levels){
$attendance = Attendance::with(['student', 'levels'])->first();
return view('admin.attendance.add', compact('students','level_id', 'levels', 'attendance'));
}
}
}
}
Here is my Attendance model
public function student()
{
return $this->belongsTo(Student::class,'student_id');
}
public function teacher()
{
return $this->belongsTo(Teacher::class, 'teacher_id');
}
public function levels()
{
return $this->belongsTo(Levels::class, 'level_id');
}
Here is my list.blade.php file of containing attendance
#section('content')
#if(session()->has('message'))
<div class="row">
<div class="col-md-12">
<div class="alert alert-success">
{{ session()->get('message') }}
</div>
</div>
</div>
#endif
#if(isset($levels) || $levels == '')
<div class="form-row justify-content-center">
<div class="form-group col-xs-6">
<label for="Date"> Please Select Date</label>
<input type="date" name="attendance_date" value="{{ date('Y-m-d') }}" class="form-control" required>
</div>
<div class="form-group col-xs-6">
<label for="Attendance">Please Select Level to see registered students</label>
<select class="form-control" id="level_id" name="student_id">
<option value="" disabled selected>Select Level</option>
#foreach($levels as $level)
<option value="{{#$level->id}}">{{#$level->level_name}}</option>
#endforeach
</select>
</div>
</div>
#endif
#stop
#section('js')
<script>
jQuery(document).ready(function($) {
// get your select element and listen for a change event on it
$('#level_id').change(function() {
// set the window's location property to the value of the option the user has selected
window.location = '/attendance/add/'+$(this).val();
});
});
</script>
#endsection
Here is my add.blade.php file containing attendance
<form action="{{ route('attendance.index') }}" method="GET" class="w-full max-w-xl px-6 py-12" enctype="multipart/form-data">
#csrf
#php
$heads = [
'Name',
'Roll Number',
'Semester',
['label' => 'Attendance', 'no-export' => true, 'width' => 5],
];
/*$btnDetails = '<button class="btn btn-xs btn-default text-teal mx-1 shadow" title="Details">
<i class="fa fa-lg fa-fw fa-eye"></i>
</button>';*/
$config = [
'data' => $students,
'order' => [[1, 'asc']],
'columns' => [null, null, null, null, ['orderable' => true]],
];
#endphp
{{-- Minimal example / fill data using the component slot --}}
<x-adminlte-datatable id="table6" :heads="$heads" head-theme="light" theme="light custom-head-theme dt-responsive"
striped>
#if($config['data'])
#foreach($config['data'] as $row)
<tr class="{{ (isset($row['status']) && $row['status']==0) ? 'table-danger' : ''}}">
<td>{!! $row['student_given_name'] !!}</td>
<td>{!! $row['student_roll_no']!!}</td>
<td>{!! $row['student_semester']!!}</td>
<td>
<nobr>
<select class="form-control" name="attendance_status" value="{{old('attendance_status'), #$attendance->attendance_status}}" id="attendance_status" required>
<option value="" {{#$attendance->attendance_status == '' ? 'selected' : ''}} disabled selected>Select Option</option>
<option value="Present" {{#$attendance->attendance_status == 'present' ? 'selected' : ''}} selected>Present</option>
<option value="Absent" {{#$attendance->attendance_status == 'absent' ? 'selected' : ''}}>Absent</option>
</select>
<input type="text" name="textinput" id="level_id" placeholder="Reason">
</nobr>
</td>
</tr>
#endforeach
#endif
</x-adminlte-datatable>
<div class="row mt-3">
<div class="col-md-12">
<div class="card-footer">
<div class="float-left col-md-4 mb-2">
<button type="submit" name="save_close" value="true" class="btn btn-primary btn-lg btn-block">Save & Close</button>
</div>
<div class="float-right col-md-4 mb-2">
<button type="button" class="btn btn-secondary btn-lg btn-block">Cancel</button>
</div>
</div>
</div>
</div>
</form>
#stop
What modifications are required in attendance controller in order to save record in table and I can view it on frontend side as well
On your AttendanceController you just show data, not insert data to database, you should get the request data and insert data to database, but first check your blade file, you must make an input for level_id, teacher_id, and student_id
to check your attachment you can use
dd($request);
die();
on your first line AttendanceController function store
public function store(Request $request, $level_id)
{
dd($request);
die();
//get form data
$data = $request->all();
//Create Student record
$students = Student::all();
$levels = Levels::all();
if($level_id){
$levels = Levels::find($level_id);
if($levels){
$attendance = Attendance::with(['student', 'levels'])->first();
return view('admin.attendance.add', compact('students','level_id', 'levels', 'attendance'));
}
}
}
if your system catch the good request
you should try this
public function store(Request $request, $level_id)
{
$levels_id = $request->level_id;
$teachers_id = $request->teacher_id;
$students_id = $request->student_id;
$data = [$levels_id,teachers_id,students_id];
attendance::create($data);
}
there's the code to save data into your laravel project, you should approve my solution

Laravel 8 form select option dropdown problem

Am having problem here
I have two tables
Department table
with fields
id dept_code dept_name
I also have Persons table
with fields
id Persons_names Dept_name Position_held
I have a data entry form to enter data to the Persons_table
the problem am having is I want to create select option to get Dept_name From Department_table but am always getting undefined value error.
this is my form
{!! Form::open(['url' => 'persons_form/store']) !!}
{{ csrf_field() }}
<div class="form-row">
<div class="form-group col-md-6">
{{Form::label('FullNames', 'Fullnames')}}
{{Form::text('names', '',['class'=>'form-control','placeholder'=>'Persons Fullnames'])}}
</div>
<div class="form-group col-md-6">
{{Form::label('Department', 'Department')}}
#foreach ($depts as $dept)
{{
Form::select('department', $dept->department_name, null, ['class'=>'form-control','placeholder' => 'Select Department'])
}}
#endforeach
</div>
<div class="form-group col-md-12">
{{Form::label('Position', 'Position')}}
{{Form::text('level', '',['class'=>'form-control','placeholder'=>'Departmental Position'])}}
</div>
</div>
<div>
{{Form::submit('Save Data',['class'=>'btn btn-outline-primary text-center',])}}
</div>
{!! Form::close() !!}
this is my personsController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\People;
class PeopleController extends Controller
{
public function index()
{
$depts = DB::table('departments')->select('department_name')->get();
return view('strategic_plan.people_form', ['depts' => $depts]);
}
public function create()
{
$depts = DB::table('departments')->pluck('department_name');
}
public function store(Request $request)
{
$this->validate($request,[
'names'=>'required',
'department'=>'required',
'level' =>'required'
]);
$persons =new People;
$persons->names=$request->input('names');
$persons->department=$request->input('persons');
$persons->level=$request->input('level');
$dept->save();
return redirect('/people')->with('message','Person Added Succesifully');
}
public function show()
{
$persons = People::all()->sortByDesc("id");
return view('strategic_plan.people',compact('persons'));
}
public function edit($id)
{
}
public function update(Request $request, $id)
{
//
}
public function destroy($id)
{
//
}
}
When I try to open the Form am getting
$depts is undefined
Try using compact, And get #dd in your blade of $depts and share the code.
Use
return view('strategic_plan.people_form', ['depts' => $depts]);
instead of
return view('strategic_plan.people_form', compact('depts');
write it down

Laravel | Save and display two relations

I'm close to finish my CMS but I have one minor problem.
I can create several teams, works perfectly fine.
I can create several games, works also perfectly fine.
Now I want to create matches between those teams, which means I have two pivot tables.
One called game_match and the other called match_team.
game_match consist of game_idand match_id
match_teamconsist of match_id, team1_idand team2_id
My match/create.blade.php has two dropdown fields for each team.
Saving a single relation to the database works fine for me as I've done this a couple of times, but I can't figure out how to save two relations.
This is what I got so far:
Inside match/create.blade.php
<div class="field m-t-20 is-inline-block">
<p class="control">
<label for="home" class="label"><b>{{ trans_choice('messages.home', 1) }}</b></label>
<input type="hidden" name="home" id="home" :value="homeSelected">
<div class="select">
<select v-model="homeSelected">
#foreach($teams as $team)
<option value="{{ $team->id }}">{{ $team->name }}</option>
#endforeach
</select>
</div>
</p>
</div>
<div class="field m-t-20 is-inline-block">
<p class="control">
<label for="opponent" class="label"><b>{{ trans_choice('messages.opponent', 1) }}</b></label>
<input type="hidden" name="opponent" id="opponent" :value="opponentSelected">
<div class="select">
<select v-model="opponentSelected">
#foreach($teams as $team)
<option value="{{ $team->id }}">{{ $team->name }}</option>
#endforeach
</select>
</div>
</p>
</div>
#section('scripts')
<script>
var app = new Vue({
el: '#app',
data: {
homeSelected: "",
opponentSelected: "",
gameSelected: ""
}
});
</script>
#endsection
MatchController.php
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required|max:255',
'matchday' => 'required',
]);
$match = new Match();
$match->title = $request->title;
$match->matchday = $request->matchday;
if ($match->save()) {
$match->games()->sync($request->game);
$match->teams()->sync( [
['team1_id' => $request->home, 'team2_id' => $request->opponent],
]);
Session::flash('success', trans('messages.created', ['item' => $match->title]));
return redirect()->route('matches.show', $match->id);
} else {
Session::flash('error', trans('messages.error'));
return redirect()->route('matches.create')->withInput();
}
}
match.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Match extends Model
{
use SoftDeletes; // <-- Use This Instead Of SoftDeletingTrait
protected $fillable = [
'title'
];
protected $dates = ['deleted_at'];
public function setHomeTeam () {}
public function teams () {
return $this->belongsToMany('App\Team', 'match_team', 'match_id', 'team1_id');
}
public function games () {
return $this->belongsToMany('App\Game', 'game_match');
}
public function getHomeTeam() {
return $this->belongsToMany('App\Team', 'match_team', 'match_id', 'team1_id');
}
public function getOpponentTeam() {
return $this->belongsToMany('App\Team', 'match_team', 'match_id', 'team2_id');
}
}
Can someone help me?
You should better use firstOrCreate(), updateOrCreate or attach() methods.

Select2 and laravel 5.3 forms

I have a laravel 5.3 app and i have a New Posts page with:
<div class="form-group col-sm-12">
<label for="tags"> Select Tags</label>
<select class="custom-select form-control" name="tags" id="tag-select" multiple="multiple">
#foreach($tags as $tag)
<option value="{{$tag->id}}">{{$tag->name}} </option>
#endforeach
</select>
</div>
Using select2 https://select2.github.io/
Tag Model
<?php
namespace App\Models;
use Eloquent as Model;
use Illuminate\Database\Eloquent\SoftDeletes;
/**
* Class tag
* #package App\Models
* #version September 20, 2016, 5:31 am UTC
*/
class tag extends Model
{
use SoftDeletes;
public $table = 'tags';
protected $dates = ['deleted_at'];
public $fillable = [
'name',
'id'
];
/**
* The attributes that should be casted to native types.
*
* #var array
*/
protected $casts = [
'name' => 'string'
];
/**
* Validation rules
*
* #var array
*/
public static $rules = [
];
public function post()
{
return $this->belongsTo('App\Models\Post');
}
public function movie()
{
return $this->belongsTo('App\Models\Movies');
}
}
At the controller when i dd(request()) i only get the value of the last tag i clicked.
Please help, how can i get the input to pass all the values and how to get them at the controller.
Anything else needed please let me know.
Thanks
Why don't you use blade templating ?
do it like so :
{{ Form::select('tags', \App\tags::all()->pluck('name', 'id')->toArray(), null,['class'=>'select2']) }}
inside your div :
<div class="form-group col-sm-12">
{{ Form::label('Select Tags', null, ['class' => 'control-label']) }}
{{ Form::select('tags[]', \App\tags::all()->pluck('name', 'id')->toArray(), null,['class'=>'select2']) }}
</div>

How to check if item exists in pivot table then show a message in the view depending on result?

I want to be able to check if the current user that is signed in has any jobs in their watchlist table. If they have I want to display a button that says "Currently watching" else have a button that says "Add to watchlist" in my view called viewListings which displays all of the listings listed in the job_listings table.
I have the logic working in the ListingController. But I need to know how I can apply this logic in my view: viewListings. How do I do this?
I have the following database setup:
ListingController:
<?php namespace App\Http\Controllers;
use App\JobListing;
use App\User;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Requests\CreateListingRequest;
use App\Watchlist;
// use Illuminate\Http\Request;
use Request;
use Session;
use Auth;
use Carbon\Carbon;
use Input;
use Redirect;
use URL;
use File;
use Hugeform;
// use Symfony\Component\HttpFoundation\File;
class ListingController extends Controller {
public function __construct()
{
// This will send the user to the login page if they are not
// logged in except for the index page
$this->middleware('auth', ['except' => ['index', 'show']]);
}
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
$listings = JobListing::all();
$joblisting_ids = JobListing::lists('job_id');
// This is the logic that is working, but need to get this to the view?
foreach ($joblisting_ids as $id) {
if (Watchlist::where('user_id', '=', Auth::user()->id)->where('job_id', '=', $id)->get()->first()) {
echo 'Currently watching this'.'<p>';
} else {
echo 'Add to watchlist'.'<p>';
}
}
// Need to pass something to the view here so I can print out if the job is in the watchlist table or not
// return view('listings.viewListings', compact('listings'));
}
viewListings.blade.php
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1 inner-content">
#if(Session::has('flash_message'))
<div class="alert alert-success listing-success" role="alert">{!! Session::get('flash_message') !!}</div>
#endif
<h2>Listings page</h2>
{!! HTML::link('/listings/create', 'Create a Job Listing', ['class' => 'btn btn-success']) !!}
{!! HTML::link('/listings/myjobs', 'My Jobs', ['class' => 'btn btn-info']) !!}
{!! HTML::link('watchlist', 'My Watchlist', ['class' => 'btn btn-primary']) !!}
<hr>
#if (Auth::check())
<h4> Welcome {{ Auth::user()->username }} </h4>
<h3> Welcome ID: {{ Auth::user()->id }} </h3>
<h3> Another Version ID: {{ Auth::id() }} </h3>
#endif
#foreach ($listings as $listing)
<div class="job-full-wrap">
<div class="col-md-10">
<div class="job-left-wrapper">
<h3>{{ $listing->position_title }} </h3>
<h5>{{ $listing->company_name }} | {{ $listing->city }} | {{ $listing->job_type }} </h5>
<!-- Need to add logic in here to show either a link or button that will say 'Add to watchlist' or 'currently watching' -->
<!-- <a class="add-watchlist" href="watchlist/add/{{ $listing->job_id }}" id="{{ $listing->job_id }}">Add to watchlist</a> -->
</div>
</div>
<div class="col-md-2">
<div class="job-right-wrapper">
<img class="img-responsive" src="{{ '../uploaded_images/'.$listing->logo_path }}" alt="">
</div>
</div>
<div class="clearfix"></div>
</div>
#endforeach
</div>
</div> <!-- End of row -->
</div>
Watchlist model:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Watchlist extends Model {
protected $primaryKey = 'job_id';
protected $table = 'watchlist';
protected $fillable = ['user_id', 'job_id'];
}
User model:
<?php namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
use Authenticatable, CanResetPassword;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['username','firstname', 'lastname', 'email', 'password', 'role'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password', 'remember_token'];
public function watchlist() {
return $this->belongsToMany('\App\JobListing', 'watchlist', 'user_id', 'job_id');
}
}
JobListing model:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class JobListing extends Model {
protected $primaryKey = 'job_id';
protected $table = 'job_listings';
protected $fillable = ['user_id', 'position_title', 'description', 'category', 'job_type',
'city','company_name','company_url','logo_path','how_to_apply', 'expiry_date', 'status'];
}
For your controller function, you can set a dynamic property on each listing item as you discover whether the listing is currently watched or not.
public function index()
{
$listings = JobListing::all();
foreach ($listings as $listing) {
if (Watchlist::where('user_id', '=', Auth::user()->id)->where('job_id', '=', $listing->job_id)->get()->first()) {
$listing->watching = true;
} else {
$listing->watching = false;
}
}
// Need to pass something to the view here so I can print out if the job is in the watchlist table or not
// return View::make('listings.viewListings')->with(['listings' => $listings]);
}
Inside your foreach loop in your view, you now have access to the property which you can check like so:
#foreach ($listings as $listing)
#if ($listing->watching)
//"Currently watching" button
#else
//"Add to watchlist" button
#endif
#endforeach

Resources