working with Laravel 5.2 and Laravel Collective here. So I have this problem - I'm trying to make a drop down (select) with the first_name and the last_name of my user but in my User table first_name and last_name are in different rows. How can i display them both together in one drop down?
Here what i Have in the controller:
'teachers'=>User::where('type','=','teacher')->lists('first_name', 'last_name','id'),
With this I only see first_name.
And in the view:
{!! Form::select('teacher_name', $teachers, null, ['class' => 'form-control']) !!}
The table structure:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('username');
$table->string('password');
$table->string('first_name', 20);
$table->string('last_name', 20);
$table->integer('class_id')
->unsigned()
->nullable();
$table->enum('type', ['admin', 'teacher', 'student']);
$table->rememberToken();
$table->timestamps();
Someone?
Attributes come in handy when doing things like this. In your teacher's model, you could put:
public function getFullNameAttribute()
{
return $this->first_name . ' ' . $this->last_name;
}
Then in your controller put:
$teachers = Teacher::lists('full_name','id');
..and your view will now work as it is.
You can try something like :
$teachers = User::where('type', 'teacher')->get();
$teachersArray = [];
foreach ($teachers as $teacher){
$teachersArray[$teacher->id] = $teacher->first_name.' '.$teacher->last_name;
}
Passing the $teachersArray to your view and in your form :
{!! Form::select('teacher_name', $teachersArray, null, ['class' => 'form-control']) !!}
Related
I have a table for data:
Schema::create('general', function (Blueprint $table) {
$table->id();
$table->string('key')->unique();
$table->longText('value')->nullable();
$table->timestamps();
});
When adding data, I get the following records in the database:
id: 2
key: country
value: ["Italy","Germany"]
Countries are now added to me through tags, like this:
$form->tags('value', __('Value'))->help('Use key `<b>Enter</b>` to add a new value')
->separators([';']);
The model has a function that receives and shares all values with the key country:
public static function getCountries()
{
$country= self::where('key', 'country')->first();
return explode(',', $country['value']);
}
And then on the blade.php page I display these countries:
#foreach(App\Models\General::getCountries() as $country)
<span>{{ $country }}</span>
#endforeach
The task is to attach a picture with a flag to each country.
I create a new model with migration to add a picture:
Schema::create('general_flags', function (Blueprint $table) {
$table->id();
$table->string('flag_image', 128);
$table->timestamps();
});
My controllers are all done correctly and pictures are added and saved.
The main question is how do I create a relation of each value from the array with the desired flag, any ideas how to do this?
The problem is that I can’t change adding countries, so I have to work with what I have.
You can make new col in general_flags named country_code then when save countries_array in general save it as associative array ['country_code' => 'country name'].
Or save image as associative array ['country_code' => 'Image'].
But, In my opinion you should make table for countries and every country has a flag.
I have a Customer model which has many Contacts. I want to create a view / list of contacts which paginated and ordered by the latest Contact.
Customer.php
public function contacts()
{
return $this->hasMany(Contact::class);
}
public function latestContact()
{
return $this->hasOne(Contact::class)->latestOfMany()->withDefault();
}
In the view, I want to show the customers like this:
#foreach ($customers as $customer)
<x-table.row wire:key="row-{{ $customer->id }}">
<x-table.cell>
{{ $customer->last_name }}, {{ $customer->first_name }}
</x-table.cell>
<x-table.cell>
{{ $customer->latestContact->contacted_at }}
</x-table.cell>
</x-table.row>
#endforeach
Table Structure
Schema::create('customers', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id');
$table->string('first_name');
$table->string('last_name');
});
Schema::create('contacts', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id');
$table->foreignId('customer_id');
$table->string('type');
$table->string('body');
$table->timestamp('contacted_at');
});
I am struggling to get the correct query for this. Here's my last try which gives me the following error:
Illuminate\Database\QueryException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'latestContact.contacted_at' in 'order clause'...
return view('livewire.dashboard', [
'customers' => Customer::with('customers.*', 'latestContact.contacted_at')
->join('contacts', 'contacts.customer_id', '=', 'customers.id')
->orderBy('latestContact.contacted_at')
->paginate(25)
]);
Appreciate your support!
I think you should rewrite your query like this
Customer::with(['contacts', 'latestContact'])
->orderBy('latestContact.contacted_at')
->paginate(25)
Updated Answer
$customers= Customer::with(['contacts', 'latestContact'=>function($query){
return $query->orderBy('contacted_at','DESC');
}])->paginate(25);
In Customer model you need to modify relation like below
public function latestContact()
{
return $this->hasOne(Contact::class)->withDefault();
}
latestOfMany Indicate that the relation is the latest single result of a larger one-to-many relationship.
latestOfMany($column = 'id', $relation = null)
I have two tables at db, one of them is named users which simply contains user information of website and the other one is tags which contains some hashtags that users can choose from them.
I also created a table named tag_user that can store the tag_id and user_id like this image:
(just like Stackoverflow that a user can select multiple tags such as php, javascript & etc)
So in order to make this relationship between these two, I added this to User model:
public function tags()
{
return $this->belongsToMany(User::class);
}
And also this one to Tag model:
public function users()
{
return $this->belongsToMany(Tag::class);
}
And here is the select option on blade, and users can select multiple tags from db:
<select class="form-control BSinaBold" name="skills[]" id="skills" multiple>
#foreach(\App\Models\Tag::all() as $tag)
<option value="{{ $tag->id }}" {{ in_array($tag->id , Auth::user()->tags->pluck('id')->toArray()) ? 'selected' : '' }}>{{ $tag->name }}</option>
#endforeach
</select>
Now as soon as I load the blade, I got this as error:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'dbname.user_user' doesn't exist (SQL: select users.*, user_user.user_id as pivot_user_id from users inner join user_user on users.id = user_user.user_id where user_user.user_id = 4)
So what's going wrong here? How can I fix this issue?
I would really appreciate any idea or suggestion from you guys...
And here is also the migration of tags & tag_user table:
public function up()
{
Schema::create('tags', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('label');
$table->timestamps();
});
Schema::create('tag_user', function (Blueprint $table) {
$table->unsignedBigInteger('tag_id');
$table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade');
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->primary(['tag_id','user_id']);
});
}
Thanks in advance.
As #aynber described in the comments:
In User model
public function tags()
{
return $this->belongsToMany(Tag::class);
}
And in Tag model
public function users()
{
return $this->belongsToMany(User::class);
}
in laravel after update existing data with other database's column information both of created_at and updated_at are updating to same value.
My Form:
{!! Form::model($user_data,array('url' => array('manageUsers', $user_data->id), 'files' => true,'method' => 'PUT', 'class'=>'validate','id'=>'xfrm_submit')) !!}
{!! Form::hidden('id',$user_data->id) !!}
<div class="form-group">
{!! Form::label( 'acceptor_name','Acceptor Name:' ) !!}
<span style="color:#ff0000;padding: 0 2px 2px 0">*</span>
<input id="acceptor_name"
name="acceptor_name"
type="text"
value="{{$user_data->acceptor_name}}">
</div>
</form>
My Controller update action :
public function update(StoreUserManagment $request)
{
$user_data = User::find($request->input('id'));
$user_data->acceptor_name =$request->input('acceptor_name');
$user_data->save();
return redirect('manageUsers');
}
Migration file:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name', '20');
$table->string('family', '25');
$table->string('username', '15')->unique();
$table->string('password', '64');
$table->string('token', '50');
$table->string('email', '20')->unique();
$table->string('remember_token', '100');
$table->string('image_file_name', '50');
$table->string('mobile_number', '13');
$table->tinyInteger('status');
$table->text('account_state_note');
$table->timestamps();
});
}
That's an issue https://github.com/laravel/framework/issues/11518
I solved this using ->nullableTimestamps() instead of ->timestamps()
You can try this,may be it will work
This is not Laravel or PHP issue but this is MySQL 5.7 change (you probably use MySQL 5.7). To solve this you need to allow timestamp to be nullable so MySQL won't fill those with current timestamps, so in Laravel you need to use nullableTimestamps() instead of timestamps() or use timestamp()->nullable() for single timestamp field.
You are calling save() instead of update() in the controller
I want to add multiple tags in mysql database table , in this case when try to add single tag then it's alright but when try to insert multiple tags show this types of error . Here is my migration and storing code .
public function store(CreateArticleRequest $request)
{
$article = Auth::user()->articles()->create($request->all());
$article->tags()->attach($request->input('tags'));
flash()->overlay('Your articles has been created!', 'Good Job');
return redirect('articles');
}
Here is migration code :
public function up()
{
Schema::create('tags',function(Blueprint $table){
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Schema::create('articles_tag',function(Blueprint $table) {
$table->increments('articles_id')->unsigned()->index();
$table->foreign('articles_id')->references('id')->on('articles')->onDelete('cascade');
$table->integer('tag_id')->unsigned()->index();
$table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade');
$table->timestamps();
});
}
Here is Form code Tag selecting box for in blade :
<div class="form-group">
{!! Form::label('tags','Tags:') !!}
{!! Form::select('tags[]',$tags,null,['class'=>'form- control','multiple']) !!}
Your migration is wrong. The table articles_tag is a pivot table, so you can't use increments for the articles_id column in that table.
To solve this, replace this line:
$table->increments('articles_id')->unsigned()->index();
with this one:
$table->integer('articles_id')->unsigned()->index();