I'm new at Laravel and not good with syntax. I have seen many tutorials and have read many answers, but still, my mind didn't get the point of how can I have a dropdown field for a foreign key.
I'm having one table "Section" and other "Class." I want to show the name of classes in section page.
Sections Migration
Schema::create('sections', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->integer('class_id')->unsigned();
$table->foreign('class_id')->references('id')->on('classses');
});
Classses Migration
Schema::create('classses', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->timestamps();
});
Honestly, I don't know if I should have changed my controller or not.
Blade/View
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" name="name" id="title">
</div>
<div class="form-group">
<label for="cid">Class</label>
???????????????
</div>
Index Function
public function index()
{ $sections = Section::all();
return view('sections.index', compact('sections'));
$classs = Classs::all()->pluck(['id', 'title']);
return view('sections.index')->with('classs', $classs); }
Error is Unreachable Statement at line $class & Expected string, got array at ([id,'title])
In your controller, you have a function to return the view.
Change it to include ->with(), so you can access the classes in the view:
// if the controller is not for the classes, add this up top:
use App\Classs; // include model name
$classs = Classs:all();
return view('yourView')->with('classe', $classs);
Then, in your view, you can just do this:
<div class="form-group">
<label for="cid">Class</label>
<select class="" name="cid">
<option value="null">Class</option>
#foreach($classs as $class)
<option value="{{$class->id}}">{{$class->title}}</option>
#endforeach
</select>
</div>
It loops over all the classes in your database and creates a <option> element for them. Looking at your first migration, you're using the id in the other table, so you need to set that as the value.
Change your index function to this:
public function index()
{
$sections = Section::all();
$classs = Class::all();
return view('sections.index')->with('sections', $sections)->with('classs', $classs);
}
Can you tell me where can I write conditions such as select * from class where role_id=2 etc.
Basically, in an MVC framework, you do all your queries in your controller and pass the data to the view, in which you display the data.
Laravel has a DB class which you can use for basic queries:
select * from class where role_id = 2
Would become this in Laravel, using the DB class.
DB::table('class')->where('role_id', 2)->get();
// or if it's a model:
Model::where('role_id', 2)->get();
I have now used this code in blade page
#php
use Illuminate\Support\Facades\DB;
$cid=DB::table('classses')->get();
$uid=DB::table('users')->where('role_id','3')->get();
$counter=0;
#endphp
<select class="" name="class_id">
<option value="null">Class</option>
#foreach($cid as $class)
#if($counter==0)
<option selected="selected" value="{{$class->id}}">{{$class->title}}</option>
{{$counter++}}
#else
<option value="{{$class->id}}">{{$class->title}}</option>
#endif
#endforeach
</select>
Related
i want to ask you how to select FOREIGN KEY (from "doa_id in "doas" table) when user create a new data (to the "notes table) in a form. This is my code :
NoteController.php
public function create()
{
return view('note/create');
}
public function store(Request $request)
{
$userId = Auth::user()->id;
Note::create([
'title' => $request->title,
'detail' => $request->detail,
'user_id' => $userId,
'mood_id' => $request->mood_id,
'doa_id' => $request->doa_id,
]);
return redirect('notes');
}
2021_05_28_020438_create_notes_table.php migration
class CreateNotesTable extends Migration
{
public function up()
{
Schema::create('notes', function (Blueprint $table) {
$table->id('note_id');
$table->string('title');
$table->date('created_at');
$table->date('updated_at');
$table->text('detail');
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
//mood FK
$table->unsignedBigInteger('mood_id');
$table->foreign('mood_id')->references('mood_id')->on('moods');
//doa FK
$table->unsignedBigInteger('doa_id');
$table->foreign('doa_id')->references('doa_id')->on('doas');
});
}
public function down()
{
Schema::dropIfExists('notes');
}
}
and this is my dropdown html :
<div class="container">
<label class="form-label text-white" style="font-weight: bold;" for="doa">Doa terkait</label>
<select class="form-select" style="color: #41A7A5" aria-label="Default select example">
<option selected>Pilih doa</option>
</select>
</div>
In Dropdown option, I want to show "doa_name" based on it's "doa_id"
Thank you :)
You can put the logic in the NoteController and the view. For example, to get a collection of all options for the foreign key, pass the collection to the view.
public function create()
{
$doas = Doas::all();
return view('note/create', compact('doas'));
}
Then on the view, you can perform a foreach loop using the select HTML tag.
<div class="container">
<label class="form-label text-white" style="font-weight: bold;" for="doa">Doa terkait</label>
<select class="form-select" style="color: #41A7A5" aria-label="Default select example">
#foreach ($doas as $doa)
<option value="{{$doa-id>}}">{{$doa->name}}</option>
#endforeach
</select>
</div>
After this, it's just using the input in your store() method.
I'm actually new to Laravel and I'm trying to build a basic social network with this Framework. For this project, I created a page called post which users can add new posts. So I tried creating the posts table like this:
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->text('caption');
$table->string('image');
$table->timestamps();
$table->index('user_id');
});
}
And on User.php model:
public function posts()
{
return $this->hasMany(Post::class);
}
And the Post.php which extends the model:
class Post extends Model
{
protected $guarded = [];
Public function user()
{
return $this->belongsTo(User::class);
}
}
And the controller which is named PostsController.php goes like this:
class PostsController extends Controller
{
public function create()
{
return view('posts.create');
}
public function store()
{
$data = request()->validate([
'caption' => 'required',
'image' => ['required','image'],
]);
auth()->user()->posts()->create($data);
dd(request()->all());
}
}
And here is the create.blade.php under the posts folder at resources dir:
#extends('layouts.app')
#section('content')
<div class="container">
<form action="/p" enctype="multipart/form-data" method="post">
#csrf
<div class="row">
<div class="col-8 offset-2">
<div class="row">
<h1>Add New Post</h1>
</div>
<div class="form-group row">
<label for="caption" class="col-md-4 col-form-label">Post Caption</label>
<input id="caption"
type="text"
class="form-control #error('caption') is-invalid #enderror"
name="caption"
value="{{ old('caption') }}"
autocomplete="caption" autofocus>
#error('caption')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="row">
<label for="image" class="col-md-4 col-form-label">Post Image</label>
<input type="file" class="form-control-file" id="image" name="image">
#error('image')
<strong>{{ $message }}</strong>
#enderror
</div>
<div class="row pt-4">
<button class="btn btn-primary">Add New Post</button>
</div>
</div>
</div>
</form>
</div>
#endsection
And if you want to take a look at routes.php here it is:
Auth::routes();
Route::get('/p/create','PostsController#create');
Route::post('/p','PostsController#store');
Route::get('/profile/{user}', 'ProfilesController#index')->name('profile.show');
So everything looks nice and clean but the problem is whenever I try to upload some dummy pictures with a caption, I see this error:
SQLSTATE[HY000]: General error: 1 table posts has no column named caption
However I tried to run php artisan migrate syntax on CMD to check if the database migration missed anything or not, and it outputs: Nothing to migrate!
So if you know why this problem occurs or how can I fix this, please let me know, I would really appreciate that!
Thanks in advance.
In your migration you need to create the relationship, like this :
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->text('caption');
$table->string('image');
$table->timestamps();
// $table->index('user_id');
});
}
Error : You make a column for foreign key, $table->unsignedBigInteger('user_id');
But you didn't define it as a foreign key with a relationship, you need to add this line for make a relation with users table as, $table->foreign('user_id')->references('id')->on('userses')->onDelete('cascade');
Laravel 7 added Foreign Key Constraints method, in this method you can define a foreign key with one line code, as :
$table->foreignId('user_id')->constrained();
This is same as :
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
The foreignId method is an alias for unsignedBigInteger while the constrained method will use convention to determine the table and column name being referenced. If your table name does not match the convention, you may specify the table name by passing it as an argument to the constrained method:
Note : MySQL makes foreign key as an index automatically, so you don't need to define , so I delete this line $table->index('user_id'); You can find more about here.
Now, if you run php artisan migrate you will get the same Nothing to migrate! , because you already migrated all tables according to your migrations, and laravel saved all your migrated files name on a table called migrations. You need to run php artisan migrate:refresh, this command will delete your all previous table and make new table.
class Post extends Model
{
protected $guarded = [];
Public function user()
{
return $this->belongsTo(User::class,'user_id', 'id');
}
}
You can try to specify the corresponding foreign key, maybe your foreign key does not specify a pair, or you can provide your User's Model to have a look
i had the same probleme and i fixed it with this commande even if it will delete ur data in ur database but it will work
php artisan migrate:refresh
I have faced this error before and all I did was run this command:
php artisan migrate:refresh
in my code,i want to show category and sub catagory under the Category in the Products table.
Here is my categories table
1.
public function up() { Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->integer('parent_id'); //sub category id
$table->string('name');
$table->rememberToken();
$table->timestamps();
});
}
Here is my products table
2.
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->integer('category_id');
$table->string('product_name');
$table->timestamps();
});
}
Here is my Category Model
3.Category.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model { protected $guarded=[];
public function products(){
return $this->hasMany('App\Product');
}
public function parent(){
return $this->belongsTo('App\Category','parent_id','id');
}
}
Here is my Product Model
4.Product.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
public function category(){
return $this->hasone('class::Category');
}
}
Now here is my ProductsController.php
5.ProductsController.php
<?php
namespace App\Http\Controllers;
use App\Category;
use App\Product;
use Session;
use Illuminate\Http\Request;
class ProductsController extends Controller
{
public function product(){
return view('admin.products.product');
}
}
Here is my product.blade.php file
<form class="form-horizontal" method="post" action="{{route('add.product')}}" name="add_product" id="add_product" novalidate="novalidate">
#csrf
<div class="control-group">
<label class="control-label">main Category </label>
<div class="controls">
<select name="category_id" id="category_id" style="width:220px;">
#foreach(App\Category::all() as $cat)
<option value="{{$cat->id}}" >{{ $cat->parent()->name ? $cat->parent()->name . ' -- ' : '' }}{{$cat->name}}</option>
#endforeach
</select>
</div>
</div>
<div class="control-group">
<label class="control-label">Product Name</label>
<div class="controls">
<input type="text" name="product_name" id="product_name">
</div>
</div>
<div class="form-actions">
<input type="submit" value="submit" class="btn btn-success">
</div>
</form>
I want to data like this in my product.blade.php
what data i want
thats why i use this code in product.blade.php
#foreach(App\Category::all() as $cat)
<option value="{{$cat->id}}" >{{ $cat->parent()->name ? $cat->parent()->name . ' -- ' : '' }}{{$cat->name}}</option>
#endforeach
but i facing error like this
ErrorException (E_ERROR)
Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$name (View: F:\laragon\www\flipcart\resources\views\admin\products\product.blade.php)
Previous exceptions
Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$name (0)
There are a number of things you may want to review in this code as there are several odd bits.
The error you are getting is caused by this code:
$cat->parent()->name
You are accessing a query builder instance when you call a relationship as a method rather than a property (i.e. ->parent() rather than ->parent).
Try this instead:
$cat->parent->name
Your ternary statement should then be replaced with something like this:
$cat->parent ? $cat->parent->name . ' -- ' : ''
I am new to laravel, I have a two tables: users, selected_users both contains id, name.
I wanted to create a drop down list that is populated from users, when selecting a user name it will insert the user's name beside the drop down menu.
When I press submit the name should be saved to the selected_user table.
Can please someone help with this code how to write it in the view and controller.
I'm not quiet sure what you really want to achieve but try the code below;
userview.blade.php
<div class="container">
#if(session('success'))
<h1>{{session('success')}}</h1>
#endif
<form method="POST" action="{{route('save.selected-user')}}">
{{ csrf_field() }}
<div class="form-group row">
<div class="col-sm-8">
<select class="form-control" id="selectUser" name="user_selected" required focus>
<option value="" disabled selected>Please select user</option>
#foreach($users as $user)
<option value="{{$user->id}}">{{ $user->name }}</option>
#endforeach
</select>
</div>
<label class="col-sm-4 col-form-label" id="displayUser">Show selected User
here</label>
</div>
<input type="submit" value="Save">
<script type="text/javascript">
var mytextbox = document.getElementById('displayUser');
var mydropdown = document.getElementById('selectUser');
mydropdown.onchange = function(){
mytextbox.value = mytextbox.value + this.value; //to appened
mytextbox.innerHTML = this.value;
}
</script>
TestController.php (make sure you have User model and SelectedUser model)
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use App\SelectedUser;
class TestController extends Controller
{
public function populateUsers()
{
$users = User::all();
return view('test.userview', compact('users'));
}
public function saveUser(Request $rq)
{
$selectedUser = new SelectedUser;
$selectedUser->name = $rq->user_selected;
$selectedUser->save();
return redirect()->back()->with('success', 'Selected Username added successfuly');
}
}
WEB.php
Route::get('/selected-user', 'TestController#populateUsers');
Route::POST('/selected-user', 'TestController#saveUser')->name('save.selected-user');
Please let me know if it works
My problem is the next in a voyager project I'm working on. I have an enterprise table and a users table.
I need to add a select input in the edit view of users table - but this view is in vendor\tcg\voyager\resources\views\users\edit-add.blade.php
I tried to add the select like:
<div class="form-group">
<label for="enterprise">Enterprises</label>
<select name="enterprise_id" id="inputEnterprise_id" class="form-control">
#foreach ($enterprises as $enterprise)
<option value="{{$enterprise['id']}}">{{$enterprise['name']}}</option>
#endforeach
</select>
</div>
I wrote the controller so it gets the data from the table. But, when I go to voyager and I try to edit some user, I have an exception error where says that the $enterprises var is not defined.
My edit() function in controller:
public function edit()
{
$enterprises = Enterprise::all();
return view('users.edit-add',compact('enterprises'));
}
Can someone tell me what the bug is?