what's wrong with my create view in laravel - laravel

I can't figure out what's wrong with my create view. I need the submit button to redirect me to my show view so I can see all the created tags.
Here are the routes to create a tag, to show the tag and then store the tag:
Route::get('/tags/create', ['uses' => 'TagController#create', 'as' => 'tags.create']); // Allows you to create a new tag
Route::post('/postTags', ['uses' => 'TagController#store', 'as' => 'postTags']); // Place where all the tags are stored
Route::get('/tag/show', ['uses' => 'TagController#show', 'as' => 'tags.show']); // Shows you all the existing tags
Here is my tag controller:
public function create()
{
$tag = new Tag();
return view('tags.create', compact('tag'));
}
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
]);
$tag = new Tag;
$tag->name = $request['name'];
$tag->save();
return redirect()->route("tags.show");
}
public function show()
{
$tags = Tag::all();
return view('tags.show', compact('tags'));
}
And my create view:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>New Tag</h1>
<form method="POST" action="{{route("postTags")}}">
{{csrf_field()}}
<label for="name">Click here to edit the title of your post!</label>
<input type="text" name="Name" id="name" required/>
<input type="submit" value="Submit" onclick="window.location='{{ route("tags.show") }}'"/>
</form>
</body>
</html>

here is the mistake, you given name="Name", the first letter is capital, and in function all are small
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
]);
$tag = new Tag;
$tag->name = $request['name'];
$tag->save();
return redirect()->route("tags.show");
}
also you are creating object in the above function without calling the constructor $tag = new Tag;, create it as $tag = new Tag();

Related

Updating many-to-many relational data with attach() from multiple checkboxes in Laravel

I am creating an online bookstore in Laravel, and upon creating a new book, the administrator is able to define which warehouses that are able to stock this book, by checking the specific warehouses checkboxes.
To give insight in how it works, this is my create function:
public function create()
{
$authors = Author::all();
$selectedAuthor = Book::first()->author_id;
$publishers = Publisher::all();
$selectedPublisher = Book::first()->publisher_id;
$warehouses = Warehouse::all();
$selectedWarehouse = Book::first()->warehouse_id;
return view('books.create', compact(['authors', 'publishers', 'warehouses'],
['selectedAuthor', 'selectedPublisher', 'selectedWarehouse']
));
}
and my store method:
public function store(Request $request)
{
$request->validate([
'ISBN' => 'required',
'author_id' => 'required',
'publisher_id' => 'required',
'year' => 'required',
'title' => 'required',
'price' => 'required',
]);
try {
$book = Book::create($request->all());
foreach ($request->checked as $value){
$book->warehouses()->attach([$value]);
}
return redirect()->route('books.index')
->with('success','Book created successfully.');
} catch (\Illuminate\Database\QueryException $e) {
var_dump($e->errorInfo);
}
}
But when an administrator edits a book, the checkboxes that were checked upon creating the book, should be "checked", and the administrator should be able to attach more warehouses, and be able to "unselect" a warehouse, so if an already checked value gets unchecked and sumbitted, it should get detached from the many-to-many table.
This is what i currently have:
My edit method:
public function edit(Book $book)
{
$authors = Author::all();
$selectedAuthor = Book::first()->author_id;
$publishers = Publisher::all();
$selectedPublisher = Book::first()->publisher_id;
$warehouses = Warehouse::all();
$selectedWarehouse = Book::first()->warehouse_id;
return view('books.edit', compact(['book', 'authors', 'publishers', 'warehouses'],
['selectedAuthor', 'selectedPublisher', 'selectedWarehouse']));
}
And my update method:
public function update(Request $request, Book $book)
{
$request->validate([
'ISBN' => 'required',
'publisher_id' => 'required',
'author_id' => 'required',
'year' => 'required',
'title' => 'required',
'price' => 'required',
]);
try {
$book->update($request->all());
// TODO: Update warehouses
return redirect()->route('books.index')
->with('success','Book updated successfully.');
} catch (\Illuminate\Database\QueryException $e) {
var_dump($e->errorInfo);
}
}
And the checkboxes in my edit.blade view:
#foreach($warehouses as $warehouse)
<input type="checkbox" name="checked[]" value="{{ $warehouse->id }}">
{{ $warehouse->address }}
<br/>
#endforeach
My Book model:
public function warehouses()
{
return $this->belongsToMany(Warehouse::class);
}
And my warehouse model:
public function books()
{
return $this->belongsToMany(Book::class);
}
Any help on being able to attach / detach upon editing an existing book, would be highly appreciated!
Try this on create and update method for storing
// Your method
foreach ($request->checked as $value){
$book->warehouses()->attach([$value]);
}
// Try This
$book->warehouses()->sync($request->checked); // $request->checked must be an array
Update Blade
#foreach($warehouses as $warehouse)
<input #if($book->warehouses()->where('warehouse_id', $warehouse->id)->exists()) checked #endif type="checkbox" name="checked[]" value="{{ $warehouse->id }}">
{{ $warehouse->address }}
<br/>
#endforeach
I will left this example with a logic according your problem. In this case are roles:
public function edit(Role $role){
//get roles ids
$permission_role = [];
foreach($role->permissions as $permission){
$permission_role[] = $permission->id;
}
//get permissions
$permissions = Permission::all();
return view("role.edit", compact('role', 'permission_role', 'permissions'));
}
In the blade:
<div class="row">
<div class="col-md-8">
<div class="form-group">
<label>Select the permissions for the current role</label>
#foreach ($permissions as $permission)
<div class="valid-feedback d-block" style="font-size: 15px !important;">
<input type="checkbox" value="{{ $permission->id }}" name="permissions[]"
#if(is_array(old('permissions')) && in_array("$permission->id", old('permissions')))
checked
#elseif(is_array($permission_role) && in_array("$permission->id", $permission_role))
checked
#endif>
<strong> {{ $permission->description }} </strong>
</div>
#endforeach
</div>
<div class="invalid-feedback d-block">
#foreach ($errors->get('permissions') as $error)
{{ $error }}
#endforeach
</div>
</div>
</div>
Of this way you can also keep the old checkboxes when nothing is select. You should validate it as required.

How to insert record in 2 tables using single form (Laravel)?

CONTROLLER
public function store_resto(Request $request){
// dd($request->all());
$restaurant = new Restaurant();
$restaurant->name = $request->input('name');
$restaurant->email = $request->input('email');
$restaurant->address = $request->input('address');
$restaurant->save();
$image = $request->hasfile('image');
$photo = rand(1,9999).'.'.$image;
$path = public_path().'/files/';
$image->move($path, $photo);
RestoImage::create([
'image'=>$image,
'resto_id'=>$restaurant->id,
]);
$request->session()->flash('status', 'Restaurant added successfully');
return redirect('list');
}
VIEW FILE
<form method="post" action="{{route('store_resto')}}" enctype="multipart/form-data">
#csrf
<div class="form-group">
<label>Resto Name</label>
<input type="name" name="name" class="form-control">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" name="email" class="form-control">
</div>
<div class="form-group">
<label>Address</label>
<input type="text" name="address" class="form-control">
</div>
<div class="form-group">
<label>Image</label>
<input type="file" name="image" class="form-control">
</div><br>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
RestoImage Model
class RestoImage extends Model
{
use HasFactory;
protected $fillable = ['image','resto_id'];
public function restaurants(){
$this->belongsTo(Restaurant::class, 'resto_id');
}
}
Restaurant Model
class Restaurant extends Model
{
use HasFactory;
public $timestamps = false;
public function menus(){
$this->hasMany(Menu::class);
}
public function restoimage(){
$this->hasOne(RestoImage::class, 'resto_id');
}
}
Each restaurant will have 1 image. When an admin submits the form, 1 record should be inserted in both tables i.e. restaurants and resto_images. I tried this way but when I submit the form, It shows error "Call to a member function move() on bool". Please correct me if I am doing wrong. Thanks in advance.
Here i Worked on your code to explain how these things works.This is an example can help you. Not for two you can add so many tables from one function of controller. Approve my answer if you find solution or reason for getting error.
You have error because code doesn't find your image format or mine:type(png, jpeg)
$photo = rand(1,9999).'.'.$image;
Solution- you have to get image format or extention by this code
$extention = $emp_image_file->getClientOriginalExtension();
Your solution should be like this
$path1 = 'assets/img/emp/';
$destinationPath1 = $path1;
$photo_file = $request->file('image');
$photo='';
if($photo_file){
$file_size = $photo_file->getSize();
$image_name = $photo_file->getClientOriginalName();
$extention = $photo_file->getClientOriginalExtension();
$photo = value(function() use ($photo_file){
$filename = time().'.'. $photo_file->getClientOriginalExtension();
return strtolower($filename);
});
$photo_file->move($destinationPath1, $photo);
}
Put js in your view file
<script type="text/javascript">
function readURL(input) {
if (input.image && input.image[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#imagePreview').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
</script>
This is you input
<input type="file" class="form-control" name="image" >
I Also Worked For Other Visitors See Once
public function store_resto(Request $request){
<!-- validation code begins -->
$this->validate($request, [
'name'=>'required|max:120',
'email'=>'required|email|unique:users',
]);
<!-- validation code ends -->
$data = $request->all();
$table1 = Required_Model1::create([
'name' =>$data['emp_name'],
'email' =>$data['email'],
]);
$table2 = Required_Model2::create([
'name' => $data['emp_name'],
'code' => $data['emp_code'],
'status' => $data['emp_status'],
'email' => $data['email'],
'gender' => $data['gender'],
'table1_id' => $table1->id,
]);
$table3 = Required_Model3::create([
'role' => $data['role'],
'table1_id' => $table1->id,
'table2_id' => $table2->id,
if(isset($table1, $table2, $table3)) {
$request->session()->flash('status', 'Restaurant added successfully');
return redirect()->route('employee-manager');
}else{
return redirect()->back();
}
}
Comment or delete this part of code if you doesn't want to validate or mandatory.
$this->validate($request, [
'name'=>'required|max:120',
'email'=>'required,
]);
Above code explains
column name must be filled with 120 characters or not be blank.
column email must be filled.
if these two doesn't satisfy it will redirect back.
This below code
If validation is set like above code this will check and work as defined. If validation is set they check two fields name and email, if they filled or not blank it will proceed further. If validation is set fields are not filled or blank they redirect back. If validation is not set it will proceed further.
if(isset($table1, $table2, $table3)) {
$request->session()->flash('status', 'Restaurant added successfully');
return redirect()->route('employee-manager');
}else{
return redirect()->back();
}
Change these two lines
<input type="name" name="name" class="form-control" required="true" />
<input type="email" name="email" class="form-control" required="true" />
Model 1 should be like this
class Required_Model1 extends Model
{
protected $fillable = ['name','email'];
}
Model 2 should be like this
class Required_Model2 extends Model
{
protected $fillable = ['name','code', 'status', 'email', 'gender', 'table1_id'];
}
Model 3 should be like this
class Required_Model3 extends Model
{
protected $fillable = ['role','table1_id', 'table2_id'];
}
Let's talk on your error as you posted
You have face error because you want to move your image name in form of boolean. Here is gave you an standard code you can use it
$path1 = 'assets/img/emp/';
$destinationPath1 = $path1;
$emp_image_file = $request->file('employee_images');
$emp_image='';
if($emp_image_file){
$file_size = $emp_image_file->getSize();
$image_name = $emp_image_file->getClientOriginalName();
$extention = $emp_image_file->getClientOriginalExtension();
$emp_image = value(function() use ($emp_image_file){
$filename = time().'.'. $emp_image_file->getClientOriginalExtension();
return strtolower($filename);
});
$emp_image_file->move($destinationPath1, $emp_image);
}
Put this in which table you wanted to save
'photo' => $emp_image,
Add this in your view make sure you edit like your requirement
<script type="text/javascript">
function readURL(input) {
if (input.employee_images && input.employee_images[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#employee_imagesPreview').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
</script>
This is input
<input type="file" class="form-control" name="employee_images" >
$image = $request->hasfile('image');
This method is a boolean method. It will return true/false. Instead use
$request->file('image');
So first, here:
$image = $request->hasfile('image');
You are setting $image to a boolean by checking if it has that file and then later you want to run move on a that boolean which is not possible. Rather do:
if($request->hasfile('image'))
{
$image = $request->file('image');
$image->move($path, $photo);
}

Ajax image upload to database not working

I am trying to upload image to database using Ajax but It store image into public/images directory only,never store image into database,I had grabbed from itsolution for test purpose but never work,Could any one tell where am I wrong?
Route
Route::get('ajaxImageUpload', ['uses'=>'AjaxImageUploadController#ajaxImageUpload']);
Route::post('ajaxImageUpload', ['as'=>'ajaxImageUpload','uses'=>'AjaxImageUploadController#ajaxImageUploadPost']);
Controller
public function ajaxImageUploadPost(Request $request) {
$validator = Validator::make($request->all(), [
'title' => 'required',
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
if ($validator->passes()) {
$input = $request->all();
$input['image'] = time() . '.' . $request->image->getClientOriginalExtension();
$request->image->move(public_path('images'), $input['image']);
AjaxImage::create($input);
return response()->json(['success' => 'done']);
}
return response()->json(['error' => $validator->errors()->all()]);
}
View
<form action="{{ route('ajaxImageUpload') }}" enctype="multipart/form-data" method="POST">
<input type="text" name="title" class="form-control" placeholder="Add Title">
<input type="file" name="image" class="form-control">
<button class="btn btn-success upload-image" type="submit">Upload Image</button>
</form>
<script>
$("body").on("click", ".upload-image", function (e) {
$(this).parents("form").ajaxForm(options);
});
var options = {
complete: function (response) {
if ($.isEmptyObject(response.responseJSON.error)) {
$("input[name='title']").val('');
alert('Image Upload Successfully.');
} else {
printErrorMsg(response.responseJSON.error);
}
}};
function printErrorMsg(msg) {
$(".print-error-msg").find("ul").html('');
$(".print-error-msg").css('display', 'block');
$.each(msg, function (key, value) {
$(".print-error-msg").find("ul").append('<li>' + value + '</li>');
});
}
</script>
Save Image Location To The Database
use intervention;
public function ajaxImageUploadPost(Request $request){
$validator = Validator::make($request->all(), ['title' => 'required','image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048']);
if ($validator->passes()) {
$image = new AjaxImage();
$image->title = $request->title;
if ($request->hasFile('image')) {
$img=$request->file('resim');
$filename=time().".".$img->getClientOriginalExtension();
$location=public_path('img/'.$filename);
Image::make($img)->save($location);
$image->image=$filename;
}
$image->save();
return response()->json(['success'=>'done']);
}
return response()->json(['error'=>$validator->errors()->all()]);
}

Call to a member function getClientOriginalName() on null when upload image use file system Laravel

I want to upload an image using Laravel storage file system in my admin data. However, there's an error when I attempt to upload an image.
Call to a member function getClientOriginalName() on null
Controller
public function store(Request $request)
{
$admin = $request->all();
$fileName = $request->file('foto')->getClientOriginalName();
$destinationPath = 'images/';
$proses = $request->file('foto')->move($destinationPath, $fileName);
if($request->hasFile('foto'))
{
$obj = array (
'foto' => $fileName,
'nama_admin' => $admin['nama_admin'],
'email' => $admin['email'],
'jabatan' => $admin['jabatan'],
'password' => $admin['password'],
'confirm_password' => $admin['confirm_password']
);
DB::table('admins')->insert($obj);
}
return redirect()->route('admin-index');
}
View
<div class="form-group">
<label for="" class="col-md-4">Upload Foto</label>
<div class="col-md-6">
<input type="file" name="foto">
</div>
</div>
Error
You can check wheather you are getting file or not by var_dump($request->file('foto')->getClientOriginalName());
And make sure your form has enctype="multipart/form-data" set
<form enctype="multipart/form-data" method="post" action="{{ url('/store')}}">
<div class="form-group">
<label for="" class="col-md-4">Upload Foto</label>
<div class="col-md-6">
<input type="file" name="foto">
</div>
</div>
</form>
Error because of client Side
<form enctype="multipart/form-data" method="post" action="{{ url('/store')}}">
<div class="form-group">
<label for="" class="col-md-4">Upload Foto</label>
<div class="col-md-6">
<input type="file" name="foto">
</div>
</div>
</form>
you ned to add enctype="multipart/form-data" inside the form
If You are using the form builder version
{!! Form::open(['url' => ['store'],'autocomplete' => 'off','files' => 'true','enctype'=>'multipart/form-data' ]) !!}
{!! Form::close() !!}
Then In your Controller You can check if the request has the file
I have Created the simple handy function to upload the file
Open Your Controller And Paste the code below
private function uploadFile($fileName = '', $destinationPath = '')
{
$fileOriginalName = $fileName->getClientOriginalName();
$timeStringFile = md5(time() . mt_rand(1, 10)) . $fileOriginalName;
$fileName->move($destinationPath, $timeStringFile);
return $timeStringFile;
}
And the store method
Eloquent way
public function store(Request $request)
{
$destinationPath = public_path().'images/';
$fotoFile='';
if ($request->hasFile('foto'))
{
$fotoFile= $this->uploadFile($request->foto,$destinationPath );
}
Admin::create(array_merge($request->all() , ['foto' => $fotoFile]));
return redirect()->route('admin-index')->with('success','Admin Created Successfully');
}
DB Facade Version
if You are using DB use use Illuminate\Support\Facades\DB; in top of your Controller
public function store(Request $request)
{
$admin = $request->all();
$destinationPath = public_path().'images/';
$fotoFile='';
if ($request->hasFile('foto'))
{
$fotoFile = $this->uploadFile($request->foto,$destinationPath );
}
$obj = array (
'foto' => $fotoFile,
'nama_admin' => $admin['nama_admin'],
'email' => $admin['email'],
'jabatan' => $admin['jabatan'],
'password' => $admin['password'],
'confirm_password' => $admin['confirm_password']
);
DB::table('admins')->insert($obj);
return redirect()->route('admin-index');
}
Hope it is clear

Undefined variable: playlists (View: C:\xampp\htdocs\laravel53\resources\views\pages\playlist\index.blade.php)

I try to made a crud but I found this error :
Undefined variable: playlists (View: C:\xampp\htdocs\laravel53\resources\views\pages\playlist\index.blade.php)
create is working... but index no...
I am using laravel 5.4
and this is my controller :
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Requests;
use Auth,
Response,
Storage,
Session,
Redirect,
Validator,
Image,
Input;
use App\Playlist;
class PlaylistsController extends Controller {
public function index() {
$playlists = Playlist::all();
return View('pages.playlist.index')->withPlaylists($playlists);
}
public function create() {
return view('pages.playlist.create');
}
public function store(\Illuminate\Http\Request $request) {
$this->validate($request, [
'title' => 'required',
'description' => 'required',
'authors' => 'required',
'date' => 'required',
'url' => 'required',
'menssage' => 'required',
]);
$input = $request->all();
Playlist::create($input);
Session::flash('flash_message', 'Video/img successfully added!');
return view('admin');
}
public function show($id) {
$playlists = Playlist::findOrFail($id);
return view('pages.playlist.show')->withPlaylits($playlists);
}
public function edit($id) {
$playlists = Playlist::findOrFail($id);
return view('pages.playlist.edit')->withPlaylits($playlists);
}
public function update(Request $request, $id) {
$playlists = Playlist::findOrFail($id);
$this->validate($request, [
'title' => 'required',
'description' => 'required',
'authors' => 'required',
'date' => 'required',
'url' => 'required',
'menssage' => 'required',
]);
$input = $request->all();
$playlists ->fill($input)->save();
Session::flash('flash_message', 'Task successfully added!');
return redirect()->back();
}
public function destroy($id) {
$playlists = Playlist::findOrFail($id);
$playlists ->delete();
Session::flash('flash_message', 'Task successfully deleted!');
return redirect()->route('playlist.index');
}
}
My index :
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
#section('content')
<h1>Task List</h1>
<p class="lead">Here's a list of all your tasks. Add a new one?</p>
<hr>
#foreach($playlists as $playlist)
<h3>{{ $playlist->title }}</h3>
<p>{{ $playlist->description}}</p>
<p>{{ $playlist->authors}}</p>
<p>{{ $playlist->date}}</p>
<p>{{ $playlist->url}}</p>
<p>{{ $playlist->menssage}}</p>
#endforeach
<p>
View Task
Edit Task
</p>
<hr>
#stop
#extends('layouts.master')
#section('content')
</body>
</html>
Controller
public function index() {
$playlists = Playlist::all();
return View('pages.playlist.index')->with(['data', $playlists]);
}
In your index blade, just do to understand, remove blade related codes.
<?php
print_r($data);
?>
OR
You can simply do
public function index() {
$playlists = Playlist::all();
return view('pages.playlist.index',['data'=>$playlists]);
}
and in your index blade just do print_r($data) and see the result and then loop through it accordingly. Remove everything from index blade because you are extending master blade there. So remove everything (HTMLs) and just write a line of code in index blade i.e. print_r($data).
You should write this in your view
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
#section('content')
<h1>Task List</h1>
<p class="lead">Here's a list of all your tasks. Add a new one?</p>
<hr>
#foreach($playlists as $playlist)
<h3>{{ $playlist->title }}</h3>
<p>{{ $playlist->description}}</p>
<p>{{ $playlist->authors}}</p>
<p>{{ $playlist->date}}</p>
<p>{{ $playlist->url}}</p>
<p>{{ $playlist->menssage}}</p>
<p>
View Task
Edit Task
</p>
#endforeach
<hr>
#stop
#extends('layouts.master')
#section('content')
</body>
</html>
And In your controller method you write this
public function index() {
$playlists = Playlist::all();
return View('pages.playlist.index', comapct('playlists'));
}
THIS WILL SOLVE YOUR PROBLEM

Resources