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
Related
I have a form that can upload images to database. I can select 1 image and upload it. My code works perfectly but I want to update my code so it can select multiple images rather than one.
Any help is appreciated, thank you.
Controller File:
public function store(Request $request){
//image validation
$animal = $this->validate(request(), [
'image' => 'sometimes|image|mimes:jpeg,png,jpg,gif,svg|max:500',
]);
//Handles the uploading of the image
if ($request->hasFile('image')){
//Gets the filename with the extension
$fileNameWithExt = $request->file('image')->getClientOriginalName();
//just gets the filename
$filename = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
//Just gets the extension
$extension = $request->file('image')->getClientOriginalExtension();
//Gets the filename to store
$fileNameToStore = $filename.'_'.time().'.'.$extension;
//Uploads the image
$path = $request->file('image')->storeAs('public/images', $fileNameToStore);
}
else {
$fileNameToStore = 'noimage.jpg';
}
}
Blade File:
<form method ="post" action="/animals" enctype="multipart/form-data">
#csrf
<label for="name">Enter Name:</label>
<input type="text" id="name" name="name" required/>
<label for="breed">Which animal are you adding to the system?</label>
<select id="breed" name="breed">
<option value="cat">Cat</option>
<option value="dog">Dog</option>
<option value="rabbit">Rabbit</option>
<option value="hamster">Hamster</option>
<label for="dob">Enter Date of Brith:</label>
<input type="date" id="dob" name="dob" required>
<label for="available">Availability:</label>
<input type="text" id="available" name="available" required>
<label for="description">Description:</label>
<input type="text" id="description" name="description" required>
<label>Please Select Images To Upload:</label>
<input type="file" name="images[]" multiple placeholder="Select multiple files"/>
<input type="submit" value="Submit">
</form>
Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Animal extends Model
{
protected $table = 'animal';
}
one way to do this task is something like the following. You can take it as an example code:
Migration:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class Animals extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('animals', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('animals');
}
}
Model Animal
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
class animal extends Model
{
use HasFactory;
protected $fillable = ['name'];
}
Controller's store method
<?php
namespace App\Http\Controllers;
use App\Models\animal;
use Illuminate\Http\Request;
class FrontController extends Controller
{
public function index(){
//return a view over here for your index
/*For Example: return view('front.animal'); where front is your folder and inside your folder there's animal.blade.php */
}
public function store(Request $request)
{
$animal = $this->validate(request(), [
'image' => 'sometimes|image|mimes:jpeg,png,jpg,gif,svg|max:500',
]);
if ($request->hasfile('images')) {
$images = $request->file('images');
foreach($images as $image) {
$filename = $image->getClientOriginalName();
//$filename = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
$extension = $image->getClientOriginalExtension();
$fileNameToStore = $filename.'_'.time().'.'.$extension;
$path = $image->storeAs('public/images', $fileNameToStore);
Animal::create([
'animal' => $fileNameToStore,
]);
}
}
return back()->with('success', 'Images uploaded successfully');
}
}
Blade Template:
<input type="file" name="images[]" multiple class="form-control" accept="image/*">
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');
}
}
Hi I am trying to insert data into db but it says:
SQLSTATE[HY000]: General error: 1364 Field 'title' doesn't have a
default value (SQL: insert into projects (owner_id, updated_at,
created_at) values (1, 2019-06-28 13:17:11, 2019-06-28 13:17:11))
I am following Laracasts Laravel from scratch tutorial
controller:
public function store()
{
$attributes = $this->validateProject();
$attributes['owner_id'] = auth()->id();
$project = Project::create($attributes);
//Project::create($attributes);
//Project::create(request(['title', 'description']));
Mail::to($project->owner->email)->send(
new ProjectCreated($project)
);
return redirect('/projects');
}
model:
protected $guarded = [];
table:
Schema::create('projects', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('owner_id');
$table->string('title');
$table->text('description');
$table->timestamps();
$table->foreign('owner_id')->references('id')->on('users')->onDelete('cascade');
});
blade file:
<form method="POST" action="/projects">
#csrf
<div class="field">
<label class="label" for="title">Title</label>
<div class="control">
<input type="text" class="input {{ $errors->has('title') ? 'is-danger' : ''}}" name="title" value="{{ old('title') }}" placeholder="Project title">
</div>
</div>
<div class="field">
<label class="label" for="title">Description</label>
<div class="control">
<textarea name="description" class="textarea {{ $errors->has('description') ? 'is-danger' : ''}}" placeholder="Project description">{{ old('description') }}</textarea>
</div>
</div>
<div class="field">
<div class="control">
<button type="submit" class="button is-link">Create Project</button>
</div>
</div>
#include('errors')
</form>
how to solve this issue
You have the field title on the projects table however you are not assigning it a value. As it is set as Not Nullable this will give this error.
You will need all attributes to be in the $fillable attribute on the model when using Project::create($attributes); which you do not seem to have.
An example of the $fillable would be :
protected $fillable = [
'title',
'description',
'owner_id',
];
There are several other potential causes however it is impossible to tell without you including your full Project model and the view which this request is from.
Edit
You will need to change your function to this :
public function store(ProjectRequest $request)
{
$attributes = $request->all();
$attributes['owner_id'] = auth()->id();
$project = Project::create($attributes);
Mail::to($project->owner->email)->send(
new ProjectCreated($project)
);
return redirect('/projects');
}
You can create the ProjectRequest class by running php artisan make:request ProjectRequest and then putting your validation rules in there instead.
Read more here.
Add your column name in fillable like this in your model (I guess your model name is Project.php)
So your model class should like this.
<?php
mnamespace App;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
protected $guarded = [];
protected $fillable = [
'title', 'owner_id','description'
];
public function owner()
{
return $this->belongsTo(User::class);
}
public function tasks()
{
return $this->hasMany(Task::class);
}
public function addTask($task)
{
$this->tasks()->create($task);
}
}
And then update your controller store method like this.
public function store(Request $request)
{
$attributes = $this->validateProject();
$attributes->owner_id = auth()->id();
$attributes->title = $this->request->title;
$attributes->description= $this->request->description;
$project = Project::create($attributes);
Mail::to($project->owner->email)->send(
new ProjectCreated($project)
);
return redirect('/projects');
}
The error itself is self explanatory, check this code:
$attributes['owner_id'] = auth()->id();
$project = Project::create($attributes);
here you are creating a new record in project table, and for that you are taking only one column i.e. owner_id, but in the table there is a column title which do not have a default value.
So either take all the column while creating a new record or provide those column a default value (null or something else).
To set null as default value in migration:
$table->string('title')->nullable();
or you can directly change the column in database and set its default value as null, see the below screenshot:
Unable to trace the problem you are facing. Give this code a try and please comment if you got any problem.
Inside your route file
Route::post('project', 'ProjectController#store')->name('project.store');
In your create view
<form method="POST" action="{{route('project.store')}}">
#csrf
<div class="field">
<label class="label" for="title">Title</label>
<div class="control">
<input type="text" class="input {{ $errors->has('title') ? 'is-danger' : ''}}" name="title"
value="{{ old('title') }}" placeholder="Project title">
</div>
</div>
...
<div class="field">
<div class="control">
<button type="submit" class="button is-link">Create Project</button>
</div>
</div>
#include('errors')
</form>
In your ProjectController
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
class UserController extends Controller{
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required|max:255',
]);
$post = Post::create([
'title' => $request->title,
'owner_id' => auth()->id()
]);
return redirect('/projects');
}
EDIT 1
In your previous code inside ProjectsController, instead of using $attributes try using
public function store()
{
$project = Project::create([
'title' => request('title'),
'owner_id' => request('owner_id')
]);
Mail::to($project->owner->email)->send(
new ProjectCreated($project)
);
return redirect('/projects');
}
EDIT 2
Instead of using create method, try this one
public function store()
{
$project = new Project();
$project->title = request('title');
$project->owner_id = request('owner_id');
$project->save();
...
}
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.
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>