[I am new in Laravel]
I am using Laravel 5.5
I have ProductController and model Product also I have two tables products and pcategories. I want to insert data into pcategories table from ProductController. How to do this properly? I have used DB::table('pcategories')->enter code hereinsert($data); but it's not inserting created_at and updated_at value.
Another question: Can I call multiple models into a controller?
This is my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Product;
use Image;
class ProductController extends Controller {
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index() {
$product->categorieslist = Product::table('pcategories')->get();
return view('product.add')->with($data);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create() {
$product->categorieslist = Product::table('pcategories')->get();
return view('product.add')->with($data);
}
public function all() {
$product->products = Product::table('products')->get();
return view('product.all', $data);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request) {
$this->validate($request, [
'producttitle' => 'required',
'price' => 'required',
'photo' => 'image|mimes:jpeg,png,jpg,gif,svg',
]);
$product = new Product;
$image = $request->file('photo');
if ($request->file('photo')) {
$product->photo = time() . '.' . $image->getClientOriginalExtension();
$imagePath = public_path('/images/product');
$img = Image::make($image->getRealPath());
$img->resize(250, 250, function ($constraint) {
$constraint->aspectRatio();
})->save($imagePath . '/' . $product->photo);
}
$product->title = $request->input('producttitle');
$product->description = $request->input('description');
$product->category = $request->input('category');
$product->price = $request->input('price');
$product->saleprice = $request->input('saleprice');
$product->weight = $request->input('weight');
$product->dimension = $request->input('dimension');
$product->color = $request->input('color');
$product->save();
return redirect('/product/')->with('success', 'Successfully Added');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id) {
$product = Product::find($id);
return view('product.show')->with('product', $product);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id) {
$data['product'] = Product::find($id);
$data['categorieslist'] = Product::table('pcategories')->get();
return view('product.edit')->with($data);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id) {
$this->validate($request, [
'producttitle' => 'required',
'price' => 'required',
'photo' => 'image|mimes:jpeg,png,jpg,gif,svg',
]);
$product = Product::find($id);
$image = $request->file('photo');
if ($request->file('photo')) {
$product->photo = time() . '.' . $image->getClientOriginalExtension();
$imagePath = public_path('/images/product');
$img = Image::make($image->getRealPath());
$img->resize(250, 250, function ($constraint) {
$constraint->aspectRatio();
})->save($imagePath . '/' . $product->photo);
}
$product->title = $request->input('producttitle');
$product->description = $request->input('description');
$product->category = $request->input('category');
$product->price = $request->input('price');
$product->saleprice = $request->input('saleprice');
$product->weight = $request->input('weight');
$product->dimension = $request->input('dimension');
$product->color = $request->input('color');
$product->save();
return redirect('/product/all')->with('success', 'Successfully Updated');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id) {
Product::find($id)->delete();
return redirect('/product/all')->with('success', 'Successfully Deleted');
}
public function category() {
$data['categories'] = DB::table('pcategories')->get();
return view('product.category')->with($data);
}
public function storecategory(Request $request) {
$this->validate($request, [
'category' => 'required',
]);
$data = array();
$data['category'] = $request->input('category');
DB::table('pcategories')->insert($data);
return redirect('/product/category')->with('success', 'Successfully Added');
}
public function categorydestroy($id) {
DB::table('pcategories')->where('id', $id)->delete();
return redirect('product/category/')->with('success', 'Successfully Deleted');
}
}
Use Eloquent Model instead of Query Builder. Fields created_at,updated_at are "part" of Eloquent. You either use Eloquent or insert manually those fields.
If you want to use Eloquent, then make two model Product and PCategory. And then insert with your model.
PCategory::create($data);
And you need to mass assigned your field on model class.If you don't want to mass assigned your fields, than do like this-
$pcategory = new PCategory();
//$pcategory->column1 = $data['column1'] or $data->column1;
$pcategory->save();
To learn more, follow this official doc.
And for your second part, Yes, You can.
First, create a proper relationship with your models ( one to many, etc. )
Second, you can use the DB::transact to insert data into multiple tables in DB. It has it's own advantages rather than just inserting Fk in tables to fill in the data. For further info you can search in google.
Related
I want to add two images. I can upload one image but if I try to add two it shows an error. I want to add two images. I can upload one image but if I try to add two it shows an error. I want to add two images. I can upload one image but if I try to add two it shows an error. I want to add two images. I can upload one image but if I try to add two it shows an error. I want to add two images. I can upload one image but if I try to add two it shows an error.
<?php
namespace App\Http\Controllers;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\Admin\StoreTagsRequest;
class ProductController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//$tags = Product::all();
//return view('products.index', compact('tags'));
$products = Product::latest()->paginate(5);
return view('products.index',compact('products'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('products.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//$tag = Product::create($request->all());
//return redirect()->route('admin.tags.index');
$request->validate([
'name' => 'required',
'detail' => 'required',
'color' => 'required',
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'imagetwo' => 'required|imagetwo|mimes:jpeg,png,jpg,gif,svg|max:512',
]);
$input = $request->all();
if ($image = $request->file('image')) {
$destinationPath = 'image/';
$profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($destinationPath, $profileImage);
$input['image'] = "$profileImage";
}
if ($imagetwo = $request->file('imagetwo')) {
$destinationPath = 'image/';
$profileImagetwo = date('YmdHis') . "." . $imagetwo->getClientOriginalExtension();
$imagetwo->move($destinationPath, $profileImagetwo);
$input['image'] = "$profileImagetwo";
}
Product::create($input);
return redirect()->route('products.index')
->with('success','Product created successfully.');
}
/**
* Display the specified resource.
*
* #param \App\Product $product
* #return \Illuminate\Http\Response
*/
public function show(Product $product)
{
return view('products.show',compact('product'));
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Product $product
* #return \Illuminate\Http\Response
*/
public function edit(Product $product)
{
return view('products.edit',compact('product'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Product $product
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Product $product)
{
$request->validate([
'name' => 'required',
'detail' => 'required',
'color' => 'required'
]);
$input = $request->all();
if ($image = $request->file('image')) {
$destinationPath = 'image/';
$profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($destinationPath, $profileImage);
$input['image'] = "$profileImage";
}else{
unset($input['image']);
}
if ($imagetwo = $request->file('imagetwo')) {
$destinationPath = 'imagetwo/';
$profileTmagetwo = date('YmdHis') . "." . $imagetwo->getClientOriginalExtension();
$image->move($destinationPath, $profileTmagetwo);
$input['imagetwo'] = "$profileTmagetwo";
}else{
unset($input['imagetwo']);
}
$product->update($input);
return redirect()->route('products.index')
->with('success','Product updated successfully');
}
/**
* Remove the specified resource from storage.
*
* #param \App\Product $product
* #return \Illuminate\Http\Response
*/
public function destroy(Product $product)
{
$product->delete();
return redirect()->route('products.index')
->with('success','Product deleted successfully');
}
function indextwo(){
//return DB::select("select * from products");
//DB::table('products')->orderBy('id','desc')->first();
return Product::orderBy('id', 'DESC')->first();
}
}
You should remove imgTwo from your validation because it does not exist, why would you put it here? tell me the reason so I can provide solution
'imagetwo' => 'required|mimes:jpeg,png,jpg,gif,svg|max:512',
I started my simple laravel project with posts. First I created my auth, than my posts and everything works fine. But I installed voyager admin panel(without dummy) in my project and I add BREAD to posts table, but when I try to Edit some of my posts it shows me an error: Call to undefined method App\Post::getTranslationsOf() (View: C:\engineering\xampp\htdocs\lsappdev\vendor\tcg\voyager\resources\views\posts\edit-add.blade.php). Why is this error showing?
Here is my PostsController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Post;
use DB;
class PostsController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth', ['except' => ['index', 'show']]);
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$posts = Post::all();
return view('posts.index')->with('posts', $posts);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('posts.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required',
'description' => 'required',
'cover_image' => 'image|nullable|max:1999'
]);
// Handle File Upload
if($request->hasFile('cover_image')){
// Get filename with the extension
$filenameWithExt = $request->file('cover_image')->getClientOriginalName();
// Get just filename
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
// Get just ext
$extension = $request->file('cover_image')->getClientOriginalExtension();
// Filename to store
$fileNameToStore= $filename.'_'.time().'.'.$extension;
// Upload Image
$path = $request->file('cover_image')->storeAs('public/cover_images', $fileNameToStore);
} else {
$fileNameToStore = 'noimage.jpg';
}
$post = new Post;
$post->title = $request->input('title');
$post->description = $request->input('title');
$post->user_id = auth()->user()->id;
$post->cover_image = $fileNameToStore;
$post->save();
return redirect('/posts');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$post = Post::find($id);
return view('posts.show')->with('post', $post);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$post = Post::find($id);
//Check if post exists before deleting
if (!isset($post)){
return redirect('/posts')->with('error', 'No Post Found');
}
// Check for correct user
if(auth()->user()->id !==$post->user_id){
return redirect('/posts')->with('error', 'Unauthorized Page');
}
return view('posts.edit')->with('post', $post);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request, [
'title' => 'required',
'body' => 'required',
'cover_image' => 'image|nullable|max:1999'
]);
$post = Post::find($id);
// Handle File Upload
if($request->hasFile('cover_image')){
// Get filename with the extension
$filenameWithExt = $request->file('cover_image')->getClientOriginalName();
// Get just filename
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
// Get just ext
$extension = $request->file('cover_image')->getClientOriginalExtension();
// Filename to store
$fileNameToStore= $filename.'_'.time().'.'.$extension;
// Upload Image
$path = $request->file('cover_image')->storeAs('public/cover_images', $fileNameToStore);
// Delete file if exists
Storage::delete('public/cover_images/'.$post->cover_image);
}
$post->title = $request->input('title');
$post->body = $request->input('description');
if($request->hasFile('cover_image')){
$post->cover_image = $fileNameToStore;
}
$post->save();
return 123;
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$post = Post::find($id);
//Check if post exists before deleting
if (!isset($post)){
return redirect('/posts')->with('error', 'No Post Found');
}
// Check for correct user
if(auth()->user()->id !==$post->user_id){
return redirect('/posts')->with('error', 'Unauthorized Page');
}
if($post->cover_image != 'noimage.jpg'){
// Delete Image
Storage::delete('public/cover_images/'.$post->cover_image);
}
$post->delete();
return redirect('/posts');
}
}
And here is my Post.php model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Laravelista\Comments\Commentable;
class Post extends Model
{
use Commentable;
protected $table = 'posts';
protected $primaryKey = 'id';
protected $fillable = ['title', 'description', 'cover_image', 'user_id'];
public function user(){
return $this->belongsTo(User::class);
}
}
Please if anybody know a solution for this error help! Everything worked fine before I installed Voyager in my project.
You are using the voyager model. So in your post model at the top
Use \TCG\Voyager\Traits\Translatable;
And inside braces
Use Translatable;
Hope it helps
I am trying to use data from two databases in laravel. Edit: I have added the products controller to the bottom of this post
This is how I test if they are linked:
<p>TEST :{{ $products->ticket->created_at}}</p>
error message:
Undefined variable: products (View: /Applications/MAMP/htdocs/lsapp/resources/views/products/create.blade.php)
Product.php (App)
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
//Table NAME
protected $table = 'products';
//PRIMARY KEY
public $primaryKey = 'id';
//Timestamps
public $timestamps =true;
public function user(){
return $this->belongsTo('App\User');
}
public function products()
{
return $this->hasMany(App\product::class);
}
}
Ticket.php (app)
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class product extends Model
{
public function Product(){
return $this->belongsTo(App\Product::class);
}
}
Product Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\product;
use App\Ticket;
class productController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth',['except' => ['index','show']]);
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$products = product::orderBy('created_at','desc')->paginate(10);
//$products = product::where('type','major')->get();
return view('products.index')->with('products',$products);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('products.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request,[
'title' => 'required',
]);
//create product
$product = new product;
$product->title = $request->input('title');
$product->venue = $request->input('venue');
$product->city = $request->input('city');
$product->country = $request->input('country');
$product->description = $request->input('description');
$product->date = $request->input('date');
$product->user_id = auth()->user()->id;
$product->save();
return redirect('/products')->with('success','product Created');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$product = product::find($id);
return view('products.show')->with('product',$product);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$product = product::find($id);
if(auth()->user()->id !==$product->user_id){
return redirect('/products')->with('error','unauthorised page');
}
return view('products.edit')->with('product',$product);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request, [
'title' => 'required'
]);
$product = product::find($id);
$product->title = $request->input('title');
$product->venue = $request->input('venue');
$product->city = $request->input('city');
$product->country = $request->input('country');
$product->description = $request->input('description');
$product->date = $request->input('date');
$product->user_id = auth()->user()->id;
$product->save();
return redirect('/products')->with('success','product updated');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$product = product::find($id);
if(auth()->user()->id !==$product->user_id){
return redirect('/products')->with('error','unauthorised page');
}
$product->delete();
return redirect('/products')->with('success','product deleted');
}
}
There are a few problems with your code.
<p>TEST :{{ $products->ticket->created_at}}</p> will never work.
Assuming you are testing in your index page, you need to loop over each product in order to see it's relationship with a ticket.
Do all of your products have a single ticket? If so, then you can just define the single ticket in a config variable. It does not make sense to define a many-to-one relationship in a database.
In your Product model, you have not defined a relationship to the Ticket model. You only have a relationship defined in the Ticket model to the Product model. This means that you can access a product from the ticket, but not the other way around. You need to explicitly define a one-on-one relationship from Product to Ticket in order to use it.
You have defined this function within the Product model.
public function products() {
return $this->hasMany(App\product::class);
}
Why? Do products themselves have many products? I think you may benefit from learning about eloquent relationships. Laracasts is a good resource for learning Laravel from scratch.
Also see Laravel official Eloquent documentation
I am student and i am new with Laravel and i have this UserController which used to assign multi Roles to User (using pivot table user_role) but i want to assign one role to each user (without pivot table) so i added role_id foreign in table user but i dont know what to change in UserController file.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use App\Role;
use DB;
use Hash;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$data = User::orderBy('id','DESC')->paginate(5);
return view('users.index',compact('data'))
->with('i', ($request->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$roles = Role::pluck('display_name','id');
return view('users.create',compact('roles'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required|email|unique:users,email',
'password' => 'required|same:confirm-password',
'roles' => 'required'
]);
$input = $request->all();
$input['password'] = Hash::make($input['password']);
$user = User::create($input);
foreach ($request->input('roles') as $key => $value) {
$user->attachRole($value);
}
return redirect()->route('users.index')
->with('success','User created successfully');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$user = User::find($id);
return view('users.show',compact('user'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$user = User::find($id);
$roles = Role::pluck('display_name','id');
$userRole = $user->roles->pluck('id','id')->toArray();
return view('users.edit',compact('user','roles','userRole'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required|email|unique:users,email,'.$id,
'password' => 'same:confirm-password',
'roles' => 'required'
]);
$input = $request->all();
if(!empty($input['password'])){
$input['password'] = Hash::make($input['password']);
}else{
$input = array_except($input,array('password'));
}
$user = User::find($id);
$user->update($input);
DB::table('role_user')->where('user_id',$id)->delete();
foreach ($request->input('roles') as $key => $value) {
$user->attachRole($value);
}
return redirect()->route('users.index')
->with('success','User updated successfully');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
User::find($id)->delete();
return redirect()->route('users.index')
->with('success','User deleted successfully');
}
}
and you can find all the code here:
http://itsolutionstuff.com/post/laravel-52-user-acl-roles-and-permissions-with-middleware-using-entrust-from-scratch-tutorialexample.html
this mean so much to me if you help me and thanks.
just now I get this issues that is bothering me.
the error in code after validator::make in update function.
BadMethodCallException in Controller.php line 107: Method [all] does
not exist.
This is the full code from BooksController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\book;
class BooksController extends Controller
{
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
$book = BooksController::all();
return view('book.index')->with('book', $book);
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
return view('book.create');
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store()
{
$rules = array(
'judul' => 'required',
'author' => 'required',
'penerbit' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
// process the login
if ($validator->fails()) {
return Redirect::to('book/create')
->withErrors($validator)
->withInput(Input::except('password'));
} else {
// store
$book = new book;
$book ->judul = Input::get('judul');
$book ->author = Input::get('author');
$book ->penerbit = Input::get('penerbit');
$book ->save();
// redirect
Session:flash('message', 'Berhasil membuat buku!');
return Redirect::to('book');
}
}
/**
* Display the specified resource.
*
* #param int $idate
* #return Response
*/
public function show($id)
{
$book = books::find($id);
return view('book.show')
->with('book', $book);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id)
{
$book = books::find($id);
return view('book.edit')
->with('book', $book);
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($id)
{
$rules = array(
'judul' => 'required',
'author' => 'required',
'penerbit' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::to('book/' . $id . '/edit')
->withErrors($validator)
->withInput(Input::except('password'));
} else {
// simpan
$book = books::find($id);
$book->judul = Input::get('judul');
$book->author = Input::get('author');
$book->penerbit = Input::get('penerbit');
$book->save();
// redirect
Session::flash('message', 'Berhasil mengganti info buku!');
return Redirect::to('book');
}
}
/**
*
* #param int $id
* #return Response
*/
public function destroy($id)
{
$book = books::find($id);
$book ->delete();
//redirect
Session::flash('message', 'Berhasil menghapus buku!');
return Redirect::to('book');
}
}
try this use Validator; instead of
use Illuminate\Support\Facades\Validator;
convert user Input::all() to input()->all() or request()->all()