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.
Related
I would like to duplicate a column on my existing seasons table using a migration in Laravel 5.5.
I can do it using SQL running these two queries:
ALTER TABLE seasons ADD uploader_channel_partner_id BIGINT NULL
then
UPDATE seasons set seasons.uploader_channel_partner_id = seasons.channel_partner_id
I am creating a system where you can transfer the ownership of videos while keeping the original uploader stored.
The up function of my migration currently just has this inside it:
Schema::create('seasons', function (Blueprint $table) {
$table->unsignedBigInteger('uploader_channel_partner_id');
$table->foreign('uploader_channel_partner_id')->references('id')->on('channel_partners');
});
EDIT:
I've made it work with this but it's slow and ugly and I'm sure there is a better way:
public function up()
{
Schema::table('seasons', function (Blueprint $table) {
$table->unsignedBigInteger('uploader_channel_partner_id')->after('channel_partner_id')->nullable();
$table->foreign('uploader_channel_partner_id')->references('id')->on('channel_partners');
});
$seasons = Season::withTrashed()->get();
foreach ($seasons as $key => $season) {
$season->uploader_channel_partner_id = $season->channel_partner_id;
$season->save();
}
}
You can use DB::raw() to force Sql to use another column instead of a string value.
Season::withTrashed()
->update([
'uploader_channel_partner_id' => DB::raw('`channel_partner_id`'),
]);
I am learning Laravel and I'm trying to create simple online store.
I created tables Items and Amounts. Now I want to display all Items with their amount in stock but for some reason unknown to me, amount of item is not fetched into items.
These are my schemas for tables:
Items:
Schema::create('items', function (Blueprint $table) {
$table->increments('id');
$table->integer('category_id')->unsigned();
$table->string('name', 120)->nullable(false);
$table->float('price',8,2)->unsigned()->nullable(false);
$table->longText('short_specification');
$table->longText('specification');
$table->longText('description');
$table->string('photo', 100);
$table->engine = 'InnoDB';
$table->foreign('category_id')->references('id')->on('categories');
});
Amounts:
Schema::create('amounts', function (Blueprint $table) {
$table->integer('item_id')->unsigned();
$table->integer('amount')->unsigned()->nullable(false);
$table->engine = 'InnoDB';
});
Schema::table('amounts',function($table){
$table->foreign('item_id')->references('id')->on('items');
$table->primary('item_id');
});
These are my models:
Item:
class Item extends Model
{
public $timestamps = false;
function amount()
{
return $this->hasOne('App\Amount','item_id','id');
}
}
Amount:
class Amount extends Model
{
function item()
{
//$this->belongsTo('App\Item');
return $this->belongsTo('App\Item','item_id','id');
}
}
When I do:
$items = DB::table('items')->get();
dd($items);
return view('home')->with('items',$items);
Items are displayed correctly, but amount of item isn't there.
When I do:
#foreach($items as $item)
{{ $item->id }}
{{ $item->amount }}
#endforeach
I get:
Undefined property: stdClass::$amount (View: D:\2.
PROGRAMY\xampp\htdocs\silicon_store\resources\views\home.blade.php)
error.
From what I've seen on the web (I've been trying to fix this for over 3 hours now so I must be doing something totally wrong) it should work properly but it isn't.
With $items = DB::table('items')->get();, you're using the query builder. It won't have the value of the relationship unless you join the amounts table in the query.
$items = DB::table('items')
->leftJoin('amounts', 'items.id', '=', 'amounts.item_id')
->get();
I think you could also use an Eloquent query. In that case each $item would be an instance of the Item model rather than a StdClass object.
$items = App\Item::with('amount')->get();
or you can use kind of this query
$items = App\Item::whereHas('amount')->get()
Here link to understanding whereHas
I have 2 table in my database.
first is table post
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->date('PostDate');
$table->string('PostTitle', 200);
$table->string('GroupID', 100)->nullable();
$table->integer('LanguageID')->default(1);
$table->timestamps();
});
second is table post_categories
Schema::create('post_categories', function (Blueprint $table) {
$table->integer('post_id');
$table->integer('category_id');
$table->timestamps();
});
Every time I store post data into database, it will stored as two rows.. because I have two active language. In my post_categories table, there has category_id column.. So, if the post data with id = 1 has 2 categories.. and the post data with id = 2 has 3 categories, it will create 5 rows in post_categories table.
But when I want to delete the post, I will check from the group ID first.. So, I will delete 2 rows too..
But the problem is, I can not delete the data in post_categories.. I have using foreach but the data won't be deleted..
This is my delete Controller:
public function destroy($id)
{
$post = Post::findOrFail($id);
Post::where('GroupID', $post->GroupID)->delete();
$postGroups = Post::where('GroupID', $post->GroupID)->get();
foreach ($postGroups as $postGroup) {
DB::table('post_categories')->where('post_id', $postGroup->id)->delete();
}
return response()->json([
"error" => "0",
"message" => "Success"
]);
}
I can delete all the post with same group ID, but I can not delete the post_categories data that has same post_id.
You've already chosen the answer, but in your case it's much better to use whereIn():
$post = Post::findOrFail($id);
$postGroups = Post::where('GroupID', $post->GroupID)->get();
DB::table('post_categories')->whereIn('post_id', $postGroups->pluck('id'))->delete();
Post::where('GroupID', $post->GroupID)->delete();
Delete the categories before deleting the post.
public function destroy($id)
{
$post = Post::findOrFail($id);
$postGroups = Post::where('GroupID', $post->GroupID)->get();
foreach ($postGroups as $postGroup) {
DB::table('post_categories')->where('post_id', $postGroup->id)->delete();
}
Post::where('GroupID', $post->GroupID)->delete();
return response()->json([
"error" => "0",
"message" => "Success"
]);
}
In order to have a better code experience, I recommend using a table structure like posts, posts_categories and posts_languages. This last one will contain the data regarding the content in multiple languages, and will be related to posts
I trying to understand laravel eloquent relationship so i created two tables. structure of tables defined in laravel migration is
for mostpopular table
Schema::create('mostpopulars',function(Blueprint $table){
$table->increments('id');
$table->integer('song_id')->unsigned();
$table->index('song_id');
$table->foreign('song_id')->references('id')->on('song_details')->delete('cascade');
});
for song_detail table
Schema::create('song_details', function (Blueprint $table) {
$table->increments('id');
$table->string('song_title');
$table->string('song_name');
$table->string('song_album');
$table->string('song_singer');
$table->string('song_musicby');
$table->string('song_location');
$table->string('song_album_image');
$table->string('song_language');
$table->string('song_lyrics',3000);
$table->timestamps();
});
then in Mostpopular model defined function for relating two table
public function song_detail()
{
return $this->hasOne('App\Song_detail','id');
}
and in controller index function i want to do something like this
$songs = Song_detail::select()->latest()->get();
$malayalamSongs = Mostpopular::select('song_id')->groupBy('song_id')->havingRaw('COUNT(*) > 2')->get();
$mp = $malayalamSongs;
dd($mp->song_detail);
but getting error
Undefined property: Illuminate\Database\Eloquent\Collection::$Song_detail
please help me to find the error and what i am trying to do is get the details of songs from song_details table where song_id occurred more than two times song_id is in mostpopular tables.
the eloquent get() will return an array, you cannot call relation method on the array.
you can use first() to replace the get() or
change
$mp = $malayalamSongs;
dd($mp->song_detail);
to
$mp = $malayalamSongs;
foreach($mp as $v)
{
dd($v->song_detail);
}
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();