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>
Related
I have this blade file witch brings the Authenticated User (Teacher), Grade and subjects he is teaching. what I want is when he clicks in the subject's button, all the users (learners) in the database which are doing that grade and subject -which is clicked- should be displayed
<div class="row">
#if(count(Auth::user()->grades) > 0)
#foreach(Auth::user()->grades as $grade)
<div class="col-md-2">
<div class="card shadow mb-4">
<div class="card-body">
<h5 class="font-weight-bold">{{$grade->name}}</h5>
<hr>
<h6 class="font-weight-bold">Subjects:</h6>
#foreach(Auth::user()->subjects as $subject)
<div class="m-2">
<button type="button" class="btn btn-outline-primary">{{ $subject->name }}</button>
</div>
#endforeach
</div>
</div>
</div>
#endforeach
#else
<h3 class="col-md-12 offset-md-5">No Grades to display</h3>
#endif
</div>
How do I send the request to the controller and the controller should query the database and bring all the required learners
public function showLearners(...)
{
//
}
The User Model
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laratrust\Traits\LaratrustUserTrait;
use App\Events\UserRegistered;
class User extends Authenticatable
{
use LaratrustUserTrait;
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $guarded = [];
/**
* The event map for the model.
*
* #var array
*/
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
'related' => 'array',
];
public function getFullNameAttribute()
{
if (is_null($this->last_name)) {
return "{$this->name}";
}
return "{$this->name} {$this->last_name}";
}
public function grades()
{
return $this->belongsToMany('App\Grade');
}
public function subjects()
{
return $this->belongsToMany('App\Subject');
}
}
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>
I want to display the role of data in a text box based on the selected user options. for example A user, role as project manager. then when selecting a user, the text box will display the role manager. but the problem is when I choose the first user, he displays the correct data in the text box. but when changing user choices, the text box does not change, only displays data based on the first choice. What is wrong.?
I want to display the role in the text box based on the user chosen
this my view
<div class="form-group">
<label>Name *</label>
<select class="form-control select2" style="width: 100%;" name="user_id" id="user_id">
<option selected="selected" value="user_id">Select One</option>
#foreach($users as $id => $user)
<option value="{{$id}}" data-price="{{$user_roles->name}}">{{$user}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="">Role *</label>
<input type="text" name="name" id="name" class="form-control" autocomplete="off" readonly>
</div>
script
<script type="text/javascript">
$('#user_id').on('change', function(){
var price = $(this).children('option:selected').data('price');
$('#name').val(price);
});
</script>
controller
$projects = Project::pluck('project_name', 'id');
$users = User::pluck('name', 'id');
$user_roles = auth()->user()->role;
return view ('teams.create', compact('projects', 'users', 'user_roles'));
model user
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Presence;
use App\Models\Project;
use App\Productivity;
use App\Sick_leave;
use App\Annual_leave;
use App\Models\Team;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'role_id',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function presence()
{
return $this->hasOne(Presence::class, 'astrowatch', 'user_id', 'presence_id');
}
public function role()
{
return $this->belongsTo(Role::class, 'role_id');
}
public function permission()
{
return $this->hasMany(Permission::class);
}
public function teams()
{
return $this->belongsToMany(Team::class, 'user_teams');
}
public function spent_time()
{
return $this->belongsToMany(Spent_time::class, 'astrowatch', 'user_id', 'spent_time_id');
}
public function projects()
{
return $this->belongsToMany(Project::Class, 'user_projects');
}
}
Change your JS to this:
$(function() {
$('#user_id').on('change', function(){
var price = $(this).data('price');
$('#name').val(price);
});
});
-- EDIT--
Change this
Controller:
$users = User::all();
View:
#foreach($users as $user)
<option value="{{$user->id}}" data-price="{{$user->role->name}}">
{{$user->name}}
</option>
#endforeach
I am trying to reproduce the exact same thing as shown in Laravel 5 fundamentals by Jeffrey Way on this link https://laracasts.com/series/laravel-5-fundamentals/episodes/22
watch closely from 10:08
but my edit form is not showing the selected tags when the form was created...i probably missed something but i just can't see it.
This is my Article Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
class Article extends Model
{
protected $fillable = [
'title',
'body',
'published_at'
];
protected $dates = ['published_at'];
public function user()
{
return $this->belongsTo(User::class);
}
public function tags()
{
return $this->belongsToMany(Tag::class);
}
public function getTagListAttribute()
{
return $this->tags->pluck('id');
}
public function setPublishedAtAttribute($date)
{
$this->attributes['published_at'] = Carbon::createFromFormat('d.m.Y H:i', $date)->format('Y-m-d H:i:s');
}
public function getPublishedAtAttribute($date)
{
return Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('d.m.Y H:i');
}
public function scopePublished($query)
{
$query->where('published_at', '<=', Carbon::now());
}
public function scopeUnpublished($query)
{
$query->where('published_at', '>', Carbon::now());
}
}
?>
Tag Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Tag extends Model
{
public function articles()
{
return $this->belongsToMany(Article::class);
}
}
ArticlesController
<?php
namespace App\Http\Controllers;
use App\Article;
use App\Http\Requests\ArticleRequest;
use Auth;
use App\Tag;
class ArticlesController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$articles = Article::latest('published_at')->unpublished()->get();
return view('articles.index', compact('articles'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$tags = Tag::pluck('name', 'id');
return view('articles.create', compact('tags'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(ArticleRequest $request)
{
//dd($request->all());
$article = Auth::user()->articles()->create($request->all());
$article->tags()->sync($request->input('tag_list'));
return redirect('articles')->with('success', "Successfully created a new Article!");
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show(Article $article)
{
return view('articles.show', compact('article'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit(Article $article)
{
$tags = Tag::pluck('name', 'id');
return view('articles.edit', compact('article', 'tags'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(ArticleRequest $request, Article $article)
{
$article->update($request->all());
$article->tags()->sync($request->input('tag_list'));
return redirect('articles')->with('success', "Successfully updated the Article!");
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy(Article $article)
{
//
}
}
?>
edit.blade.php view
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading"><h1>Edit {{ $article->title }}</h1></div>
<div class="panel-body">
{!! Form::model($article, ['method' => 'PATCH', 'action' => ['ArticlesController#update', $article->id]]) !!}
#include('articles._form', ['submitButtonText' => 'Update Article'])
{!! Form::close() !!}
</div>
</div>
</div>
</div>
</div>
#endsection
_form.blade.php partial
<div class="form-group">
{!! Form::label('title', 'Title:') !!}
{!! Form::text('title', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('body', 'Body:') !!}
{!! Form::textarea('body', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('published_at', 'Published On:') !!}
{!! Form::text('published_at', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('tag_list', 'Published On:') !!}
{!! Form::select('tag_list[]', $tags, null, ['class' => 'form-control', 'multiple']) !!}
</div>
<div class="form-group">
{!! Form::submit($submitButtonText, ['class' => 'btn btn-primary form-control']) !!}
</div>
so when i go to edit an article the multiple select tags are not selected:
It simply doesn't work and i don't know what is wrong.... If you need any other source code i will provide it.
You can do 2 things
In your model change
public function getTagListAttribute()
{
return $this->tags->pluck('id');
}
To:
public function getTagListAttribute()
{
$tags = $this->tags->pluck('id');
return $tags->all()
}
Or
2. Change your model from
public function getTagListAttribute()
{
return $this->tags->pluck('id');
}
To
public function getTagListAttribute()
{
return array_pluck($this->tags,'id);
}
You can try as:
{!! Form::select('tag_list', $tags, $article->tags->pluck('id')->all(), ['class' => 'form-control', 'multiple']) !!}
Docs
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