laravel-5.7: data is not saving into db - laravel

hi m trying to save data into db but it return only the next page without saving data into db, is there any solution to fix this problem,
controller:
public function create(Request $request)
{
if ($request->isMethod('post')) {
$data = $request->all();
$categories = new Categories;
$categories->name = $data['category_name'];
$categories_description = $data['description'];
$categories->save();
return view('admin.categories.index');
}
return view('admin.categories.create');
}
blade file:
<form class="k-form" method="post" action="{{ url('/admin/categories/index')}}" name="" id="k_form">#csrf
<div class="row">
<label class="col-3 col-form-label">Category Name:</label>
<div class="col-9">
<input class="form-control" type="text" name="category_name" value="" required="required">
</div>
</div>
<div class="form-group row">
<label class="col-3 col-form-label">Description:</label>
<div class="col-9">
<textarea name="description" required="required"></textarea>
</div>
</div>
<div class="form-group row">
<label class="col-3 col-form-label"></label>
<div class="col-9">
<div class="k-checkbox-single">
<input type="submit" value="Add Category" style="background-color: #5867dd; color: #fff; border-radius: 5px; padding: 10px;" name="">
</div>
</form>
route:
Route::match(['get', 'post'],'/admin/categories/create','CategoriesController#create');

You mistaken here
$categories_description = $data['description'];
It should be
$categories->description = $data['description'];
Hope this helps :)

Problem is in
$categories = new Categories;
I believe it should be
$categories = new Category;
or
$category = new Category; //preferred
Model is singular where as table is plural as per laravel naming convention.
Further, add column names to fillable array if you are mass assigning the values. Like
protected $fillable = ['name', 'description'];
Also, make sure your model is in App folder and you have not created any sub directories such as 'App\Models' or something.

Related

how to save multiple data using array in laravel

this is a part of my code:
<div class="row">
<div class="col-lg-2 col-md-12 col-xs-12">
<div class="form-group">
<label for="exampleInputEmail1">Title*</label>
<input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" name="title[]">
</div>
</div>
<div class="col-lg-5 col-md-12 col-xs-12">
<div class="form-group">
<label for="exampleInputEmail1">First Name*</label>
<input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" name="f_name[]">
</div>
</div>
<div class="col-lg-5 col-md-12 col-xs-12">
<div class="form-group">
<label for="exampleInputEmail1">Last Name*</label>
<input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" name="l_name[]">
</div>
</div>
</div>
and if i click add button, it will show the second form same like above. so how to save all input data into database? this is what i've done in my controller.
public function store(Request $request){
$title = $request->title;
$f_name = $request->f_name;
$l_name = $request->l_name;
$form = new Conference;
$form->name = $title.' '.$f_name.' '.$l_name;
$form->email = $request->email;
$form->phone = $request->phone;
$form->position = $request->position;
$form->category = $request->optradio;
$form->price = $request->price;
$form->t_price = $request->t_price;
$form->company = $request->company;
$form->save();
return redirect()->back()->with('message','REGISTRATION SUCCESS');
}
but it returned an error "Array to string conversion". I know i have to write something in my controller but i don't know what to do. can someone help me?
You can loop through elements and then bulk insert as below
public function store(Request $request){
$title = $request->title;
$f_name = $request->f_name;
$l_name = $request->l_name;
$data = [];
foreach($title as $key => $value) {
$data[] = [
"name" => $value." ".$f_name[$key]." ".$l_name[$key];
]
}
$Conference::insert($data);
return redirect()->back()->with('message','REGISTRATION SUCCESS');
}

Update on "user" and "technicien" with one to one connection

I have two tables user and technician with one to one connection, technician inherits from user. After editing technician information through edit form and saving no update happens on tables user and technician. and no errors as well.
Here is my code:
Controllers
public function edit($id)
{
$technicien=technicien::find($id);
$user = $technicien->user;
return view('technicien.edit',['technicien'=>$technicien])->with('user',$user);
}
public function update(Request $request, $id)
{
// do some request validation
$technicien=technicien::find($id);
$technicien->update($request->all());
$technicien->user->update($request->get('user'));
$user->nom = $request->update('nom');
return redirect('/technicien');
}
View
#extends('Layouts/app')
#extends('Layouts.master')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-10">
<h1>Modifier Technicien</h1>
<form action="{{ route('technicien.update', $technicien->technicien ) }}" method="update">
{{csrf_field()}}
{{ method_field('PATCH') }}
<div class="form-group">
<label for="nom">Nom</label>
<input id="nom" type="text" class="form-control" name="user[nom]" value="{{$user->nom}}" >
</div>
<div class="form-group">
<label for="prenom">Prenom</label>
<input id="prenom" type="text" class="form-control" name="user[prenom]" value="{{$user->prenom}}" >
</div>
<div class="form-group">
<label for="prenom">Email</label>
<input id="prenom" type="text" class="form- control" name="user[email]" value="{{$user->email}}" >
</div>
<div class="form-group">
<label for="">moyenne Avis</label>
<input type="text" name="moyenne_avis" class="form-control" value ="{{$technicien->moyenne_avis}}" >
</div>
<div class="form-group">
<label for="">Etat Technicien</label>
<input type="text" name="actif" class="form-control" value ="{{$technicien->actif}}" >
</div>
<div class="form-group">
<input type="submit" value="enregistrer" class="form-control btn btn-primary">
</div>
</div>
</form>
</div>
</div>
#endsection
Route.php
Route::get('/technicien/{id}/edit', 'TechnicienController#edit');
Route::patch('/technicien/{id}', 'TechnicienController#update')->name('technicien.update');
Model1
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class technicien extends Model
{
protected $fillable = [
'moyenne_avis', 'actif',
];
use SoftDeletes;
protected $guarded = [];
protected $dates = ['deleted_at'];
public function zoneintervention()
{
return $this->belongsToMany('App\zoneintervention','technicien_zone','technicien_id','zoneintervention_id');
}
public function metier()
{
return $this->belongsToMany('App\metier','technicien_metier','technicien_id','metier_id');
}
public function user()
{
return $this->belongsTo('App\User');
}
public function tarificationtache()
{
return $this->belongsToMany('App\tarificationtache','technicien_tarificationtache','technicien_id','tarificationtache_id');
}
}
Model2
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
public function technicien()
{
return $this->hasOne('App\technicien');
}
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'email', 'password','nom','prenom','tel','mobil','role',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
controler
public function edit($id)
{
// better to use findOrFail (it will throw an exception about missing
objects)
$technicien = technicien::findOrFail($id);
return view('technicien.edit', compact('technicien'));
}
public function update(Request $request, $id)
{
$technicien=technicien::findOrFail($id);
$technicien->user->update($request->get('user'));
$technicien->update($request->get('technicien'));
return redirect('/technicien');
}
and the view
#extends('Layouts/app')
#extends('Layouts.master')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-10">
<h1>Modifier Technicien</h1>
<form action="{{ route('technicien.update', $technicien ) }}"
method="post">
{{csrf_field()}}
{{ method_field('patch') }}
<div class="form-group">
<label for="nom">Nom</label>
<input id="nom" type="text" class="form-control"
name="user[nom]" value="{{$technicien->user->nom}}" >
</div>
<div class="form-group">
<label for="prenom">Prenom</label>
<input id="prenom" type="text" class="form-control"
name="user[prenom]" value="{{$technicien->user->prenom}}" >
</div>
<div class="form-group">
<label for="prenom">Prenom</label>
<input id="prenom" type="text" class="form-control"
name="user[tel]" value="{{$technicien->user->tel}}" >
</div>
<div class="form-group">
<label for="prenom">Prenom</label>
<input id="prenom" type="text" class="form-control"
name="user[mobil]" value="{{$technicien->user->mobil}}" >
</div>
<div class="form-group">
<label for="prenom">Prenom</label>
<input id="prenom" type="text" class="form-control"
name="user[role]" value="{{$technicien->user->role}}" >
</div>
<div class="form-group">
<label for="prenom">Email</label>
<input id="prenom" type="text" class="form-control"
name="user[email]" value="{{$technicien->user->email}}" >
</div>
<div class="form-group">
<label for="prenom">Email</label>
<input id="prenom" type="text" class="form-control"
name="user[password]" value="{{$technicien->user->password}}" >
</div>
<div class="form-group">
<label for="">moyenne Avis</label>
<input type="text" name="technicien[moyenne_avis]"
class="form-control" value="{{$technicien->moyenne_avis}}" >
</div>
<div class="form-group">
<label for="">Etat Technicien</label>
<input type="text" name="technicien[actif]"
class="form-control" value="{{$technicien->actif}}" >
</div>
<div class="form-group">
<input type="submit" value="enregistrer" class="form-
control btn btn-primary">
</div>
</form>
</div>
</div>
</div>
#endsection
Try to do with One to One relation.
Make relation for user table and technician table, then try to do update.
Try this in controller
$user = User::with('technicien')->find($id);
$data['id'] = $id;
$data = $this->validate($request, [
'moyenne_avis' => 'required',
]);
$user->technicien()->whereUserId($data['id'])->update(['moyenne_avis' => $data['moyenne_avis']
]);
return redirect('/technicien')->with('Success', 'Records updated');
Also change form method as below in ur view.blade
<form action="{{ action('TechnicienController#update', $user->id) }}" method="post">
also, instead of {{ method_field('PATCH') }} use this <input name="_method" type="hidden" value="PATCH">
Note: Table name should be plural for controller and model name.
eg: Table name: users
Controller name: UserController
Model name: User
Make sure this same in urs too.

How to display selected value and image in edit page to perform update operation using laravel

Hello,
I am new learner in Laravel and my first post in Stackoverflow so applogy to me for my mistake and English language.
I can create a project shoppingcart & perform CRUD operation where create product information such as product name, brand, description, price & image. I can done create & read operation easily. Below my product list that can be show in browser
enter image description here
When I click edit button browser can show like that below image to perform edit operation
enter image description here
where brand name & image can't shown edit product form
My productController code below like that
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\brand;
use App\Product;
use Illuminate\Support\Facades\DB;
class productController extends Controller
{
public function index(){
$product = DB::table('products')
->join('brands','products.brandID','=','brands.brandID')
-> select('products.*','brands.brandName')
->get();
return view('admin.product.productList',compact('product'));
}
public function create()
{
$product = brand::pluck('brandName','brandID');
return view('admin.product.createProduct',compact('product'));
}
public function store(Request $request)
{
// image upload
$product = $request->except('image');
$image = $request->image;
if ($image) {
$imageName = $image->getClientOriginalName();
$image->move('images', $imageName);
$product['image'] = $imageName;
}
Product::create($product);
return view('admin.product.productList', compact('product'));
}
public function show($id)
{
$product = Product::find($id);
return view('admin.product.editProduct',compact('product'));
}
public function edit($id)
{
}
public function delete($id){
$product= Product::find($id);
$data=$product->delete();
return view('admin.product.productList',compact('data'));
}
}
my editProduct.blade file code below like that
#extends('layouts.master')
#section('content')
<div class="container" align="center">
<div class="col-md-6 col-md-offset-3">
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Edit Product
</div>
<div class="panel-body">
<form action="edit" class="form-horizontal" method="POST>
{{csrf_field()}}
<div class="form-group">
<label for="name" class="col-md-4 control-label">Product Name :</label>
<div class="col-md-6">
<input id="name" type="text" class="form-control" value="{!! $product->productName !!}" name="name" required autofocus>
</div>
</div>
<div class="form-group">
<label for="name" class="col-md-4 control-label">Brand :</label>
<div class="col-md-6">
<select name=" " class="form-control" >
<option>
</option>
</select>
</div>
</div>
<div class="form-group">
<label for="description" class="col-md-4 control-label">Description:</label>
<div class="col-md-6">
<input id="description" class="form-control" name="description" value="{!! $product->description !!}" required>
</div>
</div>
<div class="form-group">
<label for="price" class="col-md-4 control-label">Price:</label>
<div class="col-md-6">
<input id="price" value="{!! $product->price !!}" class="form-control" name="price" required>
</div>
</div>
<div class="form-group">
<label for="image" class="col-md-4 control-label">Image:</label>
<div class="col-md-6">
<input id="image" type="file" value="{!! $product->image !!}" class="btn-btn-default" name="image" value="Upload" required>
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
ADD
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
#endsection
Here, brand name can be selected by HTML select attribute and value get another model Brand & the data can be retrieve from Brand model using join query which is included productController index method.
So how can I show brand name & image to edit in the editProduct blade file. Pls help me
There are couple of ways, here's 1 way.
In your controller.
public function edit($id)
{
$product = Product::find($id);
$data = [
'product_info' => $product
];
return view('your.edit.view.here', $data);
}
And inside your view, inside the FORM Tag, do the looping.
#foreach($product_info as $info)
// data info here
<input id="description" value="{{ $product->description }}" required>
#endforeach
EDIT::
Use Laravel Encryption, you need it especially web apps like shopping cart.
URL:: http://localhost:8000/product/show/encrypted_id_here
public function show($id) {
$id = decrypt($id);
}

move() function not working in laravel 5.2 while editing/updating pictures

I have a founder page where the user can upload name, information and image of the founder.
In my view when I edit pictures and upload a new one, the name of the pictures gets stored in the database but the image is not being uploaded. There must be some problem in my controller but i can't seem to find out what. Any help would be appreciated.
Below are my model, controller and view.
Founder Model
class Founder extends Model
{
protected $fillable = ['name','information', 'image'];
public function getImageAttribute()
{
if (! $this->attributes['image']) {
return 'noimage.jpg';
}
return $this->attributes['image'];
}
public function getCreatedAtAttribute($date)
{
return Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('Y-m-d');
}
public function getUpdatedAtAttribute($date)
{
return Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('Y-m-d');
}
Founder Controller
public function update(Request $request, $id)
{
$founder = Founder::find($id);
$input = $request->all();
if($file=$request->file('image'))
{
$name = $file->getClientOriginalName();
$file->move('/images/', $name);
$input['image']= $name;
}
$founder->update($request->all());
return redirect()->route('founder.view');
}
Founder View Edit Form
<form class="form-horizontal" action="/founders/{{$founder->id}}" method="POST">
{{csrf_field()}}
<input type="hidden" name="_method" value="PUT">
<div class="form-group">
<label class="col-md-12">Name</label>
<div class="col-md-12">
<input type="text" name="name" class="form-control" value="{{$founder->name}}">
</div>
</div>
<div class="form-group">
<label class="col-md-12">Information</label>
<div class="col-md-12">
<textarea class="form-control" name="information" rows="3" value="{{$founder->information}}">{{$founder->information}}</textarea>
</div>
</div>
<div class="form-group">
<label class="col-md-12">Change Image</label>
<div class="col-md-12">
<input type="file" name="image" class="form-control" value="{{$founder->image}}">
</div>
</div>
<button type="submit" name="submit" class="btn btn-success waves-effect waves-light m-r-10">Submit</button>
</form>
Try to use rename:
rename ('current/path/to/foo', 'new/path/to/foo');
Documentation: http://php.net/rename
UPDATE:
Or use variable $destinationPath:
$file->move($destinationPath, $chooseYourFileName);
Use This Method This Will Work 100%
if($request->hasFile('filename')){
$file = $request->filename;
$file_new_name = $file->move("upload/posts/", $file->getClientOriginalName());
$post->filename = $file_new_names;
}
Remember filename is your < img name="filename" >

Eloquent create not working in laravel

I am new to laravel, so I face a problem in creating a post.
Here is my route:
Route::post('savepost', 'PostsController#savepost');
Here are my createpost.blade.php
#include('header')
<div class="container">
<!-- Main component for a primary marketing message or call to action -->
<div class="jumbotron">
<h3>Create New Post</h3>
<form action="savepost" class="form-horizontal" method="post" role="form">
<div class="form-group">
<label for="inputEmail3" class="col-sm-4 control-label">Post Title</label>
<div class="col-sm-8">
<input type="text" class="form-control" name="title" id="inputEmail3" placeholder="Enter New Title">
</div>
#if($errors->has('title'))
<p class="alert alert-danger"><strong>oopps! </strong>{{ $errors->first('title') }} </p>
#endif
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-4 control-label">Post Description</label>
<div class="col-sm-8">
<textarea name="description"></textarea>
</div>
#if($errors->has('description'))
<p class="alert alert-danger"><strong>oopps! </strong>{{ $errors->first('description') }} </p>
#endif
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-8">
<input type="submit" class="btn btn-default" value="Save Post">
</div>
</div>
</form>
</div>
</div> <!-- /container -->
#include('footer')
Here are my PostsController
class PostsController extends BaseController{
public function createpost(){
return View::make('createpost');
}
public function savepost(){
$input = Input::all();
$validation = Validator::make($input, Posts::$rules);
if ($validation->passes())
{
Posts::create(array(
'title'=>Input::get('title'),
'description'=>Input::get('description')
));
}
else{
return Redirect::route('createpost')->withErrors($validation);
}
}
}
Here are my Model:
class Posts extends Eloquent {
protected $guarded = array();
protected $fillable = array('name', 'description');
protected $table = 'posts';
public static $rules = array(
'title' => 'required|min:5',
'description' => 'required'
);
}
and here are my posts database
id title description url date
please help me
Your posts table is missing the default laravel timestamps. Either turn them off in your model by doing:
public $timestamps = false;
Or add them to your posts table:
alter table posts add created_at datetime NOT NULL
alter table posts add updated_at datetime
Or create your own timestamps in your model. I see you have a date column, so you can do something like:
const CREATED_AT = 'date';
You can't use both fillable and guarded.
Of course, you should use either $fillable or $guarded - not both.
https://laravel.com/docs/5.3/eloquent#mass-assignment

Resources