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();
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)
There has been lot of issues on this but i am following the exact procedure to solve this issue as described in the other related S.O questions yet i get the same error.
Shop
public function products()
{
return $this->hasMany('App\Product');
//->withTimestamps();
}
Product
public function shop()
{
return $this->belongsTo('App\Shop');
//->withTimestamps();
}
This is how my schema looks like
Schema::create('products', function (Blueprint $table) {
$table->increments('product_id');
$table->integer('shop_id')->unsigned()->nullable();
$table->foreign('shop_id')->references('id')->on('shops');
$table->timestamps();
);
Controller
$products = new Product(array(
'name' => $request->('name');
));
$shop->products()->save($products);
After submitting my form data into the products table, i get an error Column not found: 1054 Unknown column 'id' in 'where clause'. Laravel by default seems to take id by default as my primary key but then it is product_id.
In my model, i have specified protected $primaryKey = 'product_id' and it wouldn't solve my problem. What am i doing differently ?
In the relationships you have to specify the name of the primary key when it is not called id, try to change the model like this:
SHOP
public function products()
{
return $this->hasMany('App\Product', 'product_id');
//->withTimestamps();
}
PRODUCT
public function shop()
{
return $this->belongsTo('App\Shop', 'product_id');
//->withTimestamps();
}
In the documentation explains how it works:
https://laravel.com/docs/5.5/eloquent-relationships#one-to-many
If you are using resoure routes, then you need to specify the route key name as well:
public function getRouteKeyName()
{
return 'product_id';
}
I had tried with my local with following:
Schema:
Schema::create('shops', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Schema::create('products', function (Blueprint $table) {
$table->increments('product_id');
$table->string('name');
$table->integer('shop_id')->unsigned()->nullable();
$table->foreign('shop_id')->references('id')->on('shops');
$table->timestamps();
});
Model relationship exactly same as your post.
Controller code:
$shop = new Shop;
$shop->name = 'test';
$shop->save();
$products = new Product;
$products->name = 'test';
$shop->products()->save($products);
And final result? It is saved into products table without error.
I am using Laravel 5.4 at my local.
When it stated Unknown column 'id' in 'where clause' but does it stated is products table? Can you show the full Sql error log?
I suspect it might be other relationship caused the error.
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
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']) !!}