Laravel insert data to multiple relational tables with a single form - php

I'm working on Laravel project and i would like to know:
how to insert data to my multiple related tables ?
How can we insert author id in the author_type_id field of the Author table?
How to store author_id in post?
So idon't know how to insert related models using a form. thanks for your help :)
my models
//Post model
class Post extends Model
{
//
protected $fillable = [
'post_type_id','author_id','author_type_id','article'
];
public function posttype()
{
return $this->belongsTo(Posttype::class);
}
public function author()
{
return $this->belongsTo(Author::class);
}
public function authortype()
{
return $this->belongsTo(Authortype::class);
}
}
//Posttype model
class Posttype extends Model
{
//
protected $fillable = [
'post_type'
];
public function posts()
{
return $this->hasMany(Post::class);
}
}
//author model
class Author extends Model
{
//
protected $fillable = [
'author_name','author_first_name','author_type_id'
];
public function posts()
{
return $this->belongsToMany(Post::class);
}
public function authortype()
{
return $this->belongsTo(Authortype::class);
}
}
//Authortype model
class Authortype extends Model
{
//
protected $fillable = [
'author_type '
];
public function author()
{
return $this->hasMany(Author::class);
}
public function posts()
{
return $this->hasMany(Post::class);
}
}
// PostsController Contoller
class PostsController extends Controller
{
public function index()
{
return view('index')->with('posts',Post::all());
}
public function create()
{
return view('create')->with('posttypes',$posttypes)
->with('authors',$authors)
->with('authortypes',$authortypes);
}
public function store(Request $request)
{
$this->validate($request,[
"post_type_id" => "required",
"author_id" => "required",
"author_type_id" => "required",
"article" => "required"
]);
//How can we insert author id in the author_type_id field of the Author table?
$post = Post::create([
"post_type_id" => $request->post_type_id,
"author_id" => $request->author_id,
"author_type_id" => $request->author_type_id,
"article" => $request->article,
]);
return redirect()->back();
}
}
//create post blade
#section('content')
<div class="container">
<form action="{{route('store')}}" method="POST" enctype="multipart/form-data">
{{ csrf_field()}}
<div class="form-group">
<label for="posttype">Post Type</label>
<select class="form-control" id="posttype" name="post_type_id">
#foreach ($posttypes as $posttype)
<option value="{{$posttype->id}}">{{$posttype->post_type}}</option>
#endforeach
</select>
</div>
//author type for author model (author_type_id)
<div class="form-group">
<label for="authortype">Author Type</label>
<select class="form-control" id="authortype" name="author_type_id">
#foreach ($authortypes as $authortype)
<option value="{{$authortype->id}}">{{$authortype->author_type}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="author_name">Author Name</label>
<input type="text" class="form-control" name="author_name" placeholder="your name">
</div>
<div class="form-group">
<label for="author_first_name">Author First Name</label>
<input type="text" class="form-control" name="author_first_name" placeholder="your first name">
</div>
//How to store author_id in post
<div class="form-group">
<label for="content">article</label>
<textarea class="form-control" name="article" rows="8" cols="8"></textarea>
</div>
<button type="submit" class="btn btn-primary">{{__('main.save')}}</button>
</form>
</div>
#endsection

I found solution, May this can help you in future.
$author = Author::create([
'author_type_id' => $request->author_id,
]);
$post = Post::create([
"post_type_id" => $request->post_type_id,
"author_id" => $author->id,
"author_type_id" => $request->author_type_id,
"article" => $request->article,
]);
Auther::create([
'author_type_id' => $request->author_id,
]);

Related

How do I list my foreign keys in my customer registration view with Laravel?

Is the relationship working in the bank, but I can't show it in my registration view?
Usuario.php
class Usuario extends Model
{
protected $fillable = [
'company',
'name',
'document',
'phone',
'email'
];
public function empresa()
{
return $this->belongsTo('App\Empresa');
}}
Empresa.php
class Empresa extends Model
{
protected $fillable = [
'name',
'uf',
'cnpj'
];
public function usuarios()
{
return $this->hasMany('App\Usuario');
}}
form.blade.php
#foreach($usuarios as $u)
<option value="{{ $u->company_id->name }}">{{ $u->company_id->name }}</option>
#endforeach
UsuarioController.php
class UsuariosController extends Controller
{
public function new(){
$usuarios = Usuario::get();
return view('usuarios.form', ['usuarios' => $usuarios]);
}
enter image description here
please change your empresa() method in Usuario class.
public function empresa()
{
return $this->belongsTo('App\Empresa', 'company');
}
and blade file will be changes like this.
#foreach($usuarios as $u)
<option value="{{ $u->empresa->name }}">{{ $u->empresa->name }}</option>
#endforeach
form.blade.php
#csrf
<div class="form-group">
<label for="exampleInputEmail1">Empresa:</label>
<select name="company" class="form-control">
#foreach($usuarios as $u)
<option value="{{ $u->empresa->name }}">{{ $u->empresa->name }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Nome:</label>
<input type="text" name="name" class="form-control">
</div>
UsuarioController.
class UsuariosController extends Controller
{
public function index(){
$usuarios = Usuario::get();
return view('usuarios.list', ['usuarios' => $usuarios]);
}
public function new(){
$usuarios = Usuario::get();
return view('usuarios.form', ['usuarios' => $usuarios]);
}
public function adicionar( Request $request ){
$usuario = new Usuario;
$usuarios = Usuario::get();
$usuario = $usuario->create( $request->all() );
return Redirect::to('/usuarios', ['usuarios' => $usuarios]);
}
public function editar( $id ){
$usuario = Usuario::findOrFail( $id );
return view('usuarios.form', ['usuario' => $usuario]);

Record is not added in to the database codeigniter 4

i am a begineer of codeigniter 4.i had a problem is Record is not added in to the database. i got the url link like this http://localhost:8080/index.php/usersCreate error said Whoops!
We seem to have hit a snag. Please try again later... . i don't know how to solve problem what i tried so far i attached below.
View
User.php
<form method="post" id="add_create" name="add_create" action="<?php echo site_url('usersCreate');?>">
<div class="form-group col-md-6">
<label>First Name</label>
<input type="text" name="empid" class="form-control" id="fname" placeholder="fname">
</div>
<div class="form-group col-md-6">
<label>Last Name</label>
<input type="text" name="lname" class="form-control" id="lname" placeholder="lname">
</div>
<div class="form-group col-md-6" align="center">
<Button class="btn btn-success" style="width: 80px;">Submit</Button>
</div>
</form>
Controller
User.php
public function index()
{
return view('User');
}
// insert data
public function store() {
$userModel = new UserModel();
$data = [
'fname' => $this->request->getVar('fname'),
'lname' => $this->request->getVar('lname'),
];
$userModel->insert($data);
return $this->response->redirect(site_url('users'));
}
UserModel
<?php
namespace App\Models;
class UserModel extends Model
{
protected $table = 'records';
protected $primaryKey = 'id';
protected $allowedFields = ['fname', 'lname'];
}
Routes
$routes->get('/', 'User::index');
$routes->post('usersCreate', 'User::store');
I don't know CodeIgniter per se, but you should figure out how to get more meaningful data. Is your environment set to development environment? Usually you will get more info than Whoops! We seem to have hit a snag. Please try again later... and get more details on the error.
But I see you're trying to go to the page, where you add a user. There's 2 ways to methods to reach that page, GET (this is when you just go to the page as usual) and POST (this is when you submit the form).
But the request data will only be available if you submit the form. Thus you have to differentiate between the 2 methods. In your Controller you need to do something like
if ($this->request->getMethod() === 'post') { ... }
which is when you submit the form.
Check out https://codeigniter.com/user_guide/tutorial/create_news_items.html which should have more info. Snippet
public function create()
{
$model = new NewsModel();
if ($this->request->getMethod() === 'post' && $this->validate([
'title' => 'required|min_length[3]|max_length[255]',
'body' => 'required'
]))
{
$model->save([
'title' => $this->request->getPost('title'),
'slug' => url_title($this->request->getPost('title'), '-', TRUE),
'body' => $this->request->getPost('body'),
]);
echo view('news/success');
}
else
{
echo view('templates/header', ['title' => 'Create a news item']);
echo view('news/create');
echo view('templates/footer');
}
}
I normally use a short method to get data and then submit it to the database. Here is what id do. check this. I am just updating your code
// insert data
public function store() {
$userModel = new \App\Models\UserModel();
$data = [
'fname' => $this->request->getPost('fname'),
'lname' => $this->request->getPost('lname'),
];
$userModel->insert($data);
return redirect()->to(site_url('users'));
}
then check you html file you are missing the firstname name
Try this one
<form method="post" id="add_create" action="<?php echo site_url('usersCreate');?>">
<div class="form-group col-md-6">
<label>First Name</label>
<input type="text" name="fname" class="form-control" id="fname" placeholder="fname">
</div>
<div class="form-group col-md-6">
<label>Last Name</label>
<input type="text" name="lname" class="form-control" id="lname" placeholder="lname">
</div>
<div class="form-group col-md-6" align="center">
<button type="submit" class="btn btn-success" style="width: 80px;">Submit</button>
</div>
</form>
For the check your model i think is not configured well check this one
namespace App\Models;
use CodeIgniter\Model;
class UserModel extends Model
{
protected $table = 'users';
protected $primaryKey = 'id';
protected $returnType = 'object';
protected $useSoftDeletes = false;
protected $allowedFields = ['fname', 'lname', 'email']; // did you add this side of the site model
protected $useTimestamps = false;
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $deletedField = 'deleted_at';
protected $validationRules = [];
protected $validationMessages = [];
protected $skipValidation = false;
}
Check my code if it did not help you call my attentions okay. I am still ready to help

dropdown list with several times the same item

Below my drop-down list is not displaying correctly and I don't know where the problem is. Could it be in my SerieController? I want to create an edit/update system but I've had no success.
SerielController
public function edit($id)
{
$series = Serie::find($id);
$marks = Mark::find($id);
return view('admin.series.edit', compact('series', 'marks'));
}
public function update(Request $request, $id)
{
$request->validate([
'name' => 'required|string',
'fk_mark' => 'required'
]);
$series = Serie::find($id);
$marks = Mark::find($id);
$series->name = $request->get('name');
$series->fk_mark = $request->get('fk_mark');
$series->save();
return redirect()->route('series.index')
->with('success', 'updated successfully');
}
file series.edit.blade
<form class="panel-body" action="{{route('series.update',$series->id)}}" method="POST">
<input name="_method" type="hidden" value="PATCH">
#csrf
<fieldset class="form-group">
<label for="form-group-input-1">Name</label>
<input type="text" name="name" class="form-control" id="form-group-input-1" value="{{$series->name}}">
</fieldset>
<div class="form-group">
<label for="company-content">Select Mark</label>
<select name="fk_mark" id="" class="form-control">
#foreach($series->marks as $mark)
<option value="{{$marks->id}}">
{{$marks->name_mark}}
</option>
#endforeach
</select>
</div>
Model Serie
class Serie extends Model
{
protected $fillable = ['name', 'fk_mark'];
public function marks(){
return $this->belongsTo('App\Mark', 'fk_mark');
}
}
Serie Mark
class Mark extends Model
{
protected $fillable = ['name_mark'];
public function series(){
return $this->hasMany('App\Serie', 'fk_mark');
}
public function cars(){
return $this->hasMany('App\Car','fk_serie');
}
}
Thank you a lot for your help.
In your foreach you made a mistake, the variable should be $mark not $marks
<select name="fk_mark" id="" class="form-control">
#foreach($marks as $mark)
<option value="{{$mark->id}}">
{{$mark->name_mark}}
</option>
#endforeach
</select>
In your edit function you're sending just one Mark to your view, you need to send them all if you want all marks in your select.
public function edit($id)
{
$series = Serie::find($id);
$marks = Mark::all();
return view('admin.series.edit', compact('series', 'marks'));
}

DropDown list for foreign key

I would like to learn to create a dropdown list with a foreign key on Laravel.
For information, I have a table named series with 3 fields id, name, fk_mark.
Then, I have another table named marks with 2 fields id, name_mark.
My create works correctly, here is the proof.
I am stuck about the dropdownlist, what is the syntax please for my foreign key ?
<fieldset class="form-group">
<label for="form-group-input-1">Name serie</label>
<input type="text" name="name" class="form-control" id="form-group-input-1">
</fieldset>
<fieldset class="form-group">
<label for="form-group-input-1">FK Mark</label>
<input type="text" name="fk_mark" class="form-control" id="form-group-input-1">
</fieldset>
I have tried this but without result...
<div class="form-group">
<label for="company-content">Select compagny</label>
<select name="fk_mark" class="form-control">
#foreach($series as $serie)
<option value="{{$serie->id}}"> {{$serie->name}} </option>
#endforeach
</select>
</div>
Here is my Models
Model Mark
class Mark extends Model
{
protected $fillable = ['name_mark'];
public function series(){
return $this->hasMany('App\Serie', 'fk_mark');
}
}
Model Serie
class Serie extends Model
{
protected $fillable = ['name', 'fk_mark'];
public function marks(){
return $this->belongsTo('App\Mark', 'fk_mark');
}
}
SerieController
public function index()
{
$series = Serie::oldest()->paginate(5);
return view('admin.series.index', compact('series'))
->with('i', (request()->input('page', 1)-1)*5);
}
public function create()
{
return view('admin.series.create');
}
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'fk_mark' => 'required'
]);
Serie::create($request->all());
return redirect()->route('series.index')
->with('success', 'save');
}
Thank you very much for your help.

No query results for model [User] | laravel

I'm a newbie to Laravel so I'm not yet familiar with the errors it's returning, I hope someone can help me with this.
So I created a simple app with registration form and a login form and the registered user can post whatever he/she wants but I'm getting this error
This is the form where the user can post:
#section('content')
<section class="header">
<ul>
<li></li>
<li>Back to Profile</li>
</ul>
</section>
<div class="newpost">
<h3>What new today?</h3><br>
<form action="{{URL::route('createPost')}}" method="post" autocomplete="off">
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" id="title" name="title" placeholder="Title..." required>
</div>
<div class="form-group">
<label for="content">Write Report</label>
<textarea class="form-control" name="content" id="content" placeholder="Write Here..." rows="10"></textarea>
</div>
<button type="submit" class="btn2">Publish</button>
</form>
</div>
#stop
This is the route:
Route::get('/Newpost', array(
'uses' => 'LoginUsersController#newPost',
'as' => 'newPost'
));
Route::post('/CreatePost/{id}', array(
'uses' => 'LoginUsersController#createPost',
'as' => 'createPost'
));
and the controller
public function createPost($id)
{
$users = User::findOrFail($id);
$post = array(
'title' => Input::get('title'),
'content' => Input::get('content')
);
$posts = new Post($post);
$user->post()->save($post);
dd($post);
}
and the User model where I'm guessing is causing the error.
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
protected $fillable = array('email', 'password');
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
public function getRememberToken()
{
return $this->remember_token;
}
public function setRememberToken($value)
{
$this->remember_token = $value;
}
public function getRememberTokenName()
{
return 'remember_token';
}
public function Post()
{
return $this->hasMany('Post', 'user_id');
}
}
Can someone please explain to me why I'm getting this error? Thanks
This error is caused because findOrFail can't find anything. So it fails.
If your route depends on the users id. You actually have to pass it along when creating your form:
<form action="{{URL::route('createPost', Auth::id())}}" method="post" autocomplete="off">
(Auth::id() retrieves the id of the current logged in user)
However instead, I suggest that you remove the user id from the createPost route and work with the currently logged in user directly in the controller:
Route::post('/CreatePost', array(
'uses' => 'LoginUsersController#createPost',
'as' => 'createPost'
));
And then:
public function createPost()
{
$user = Auth::user();
$post = array(
'title' => Input::get('title'),
'content' => Input::get('content')
);
$posts = new Post($post);
$user->post()->save($post);
dd($post);
}

Categories