Laravel auth on existing project - laravel

I have been working on a 'laravel' project and now want to implement an authentication. I have done 'make:auth' and the folders, routes, views etc show in the project as expected.
I have added links to login and register at the top of my homepage. When either of these links are selected they try to redirect as you would expect... So clicking login is changing URL to /login, however, I am not seeing the login page content. I get the following error message:
Trying to get property of non-object
And it has highlighted <?php echo e($film->title); ?> which is on my comments page.
I don't mind if the user is able to view all the pages and content when not logged in. I am just adding auth so that I can store comments against a user.
Why is it giving me this error / how can I fix it?
Routes:
/* display list of all films*/
Route::get('/', 'FilmsController#display');
/* display film comments*/
Route::get('/{id}', 'FilmsController#comment');
Route::post('/{id}', 'FilmsController#addComment')->name('addComment');
Route::get('/delete/{id}', 'FilmsController#deleteComment')->name('deleteComment');
Route::get('/update/{id}', 'FilmsController#editComment')->name('editComment');
Route::post('/update/{id}', 'FilmsController#saveComment')->name('saveComment');
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Home page view:
<!doctype html>
<html lang="{{ app()->getLocale() }}">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Films</title>
</head>
<body>
<div class="flex-center position-ref full-height">
#if (Route::has('login'))
<div class="top-right links">
#auth
Home
#else
Login
Register
#endauth
</div>
#endif
<h1>Films</h1>
<table id="myTable">
<tr>
<th>Title</th>
<th>Director</th>
<th>Description</th>
<th>Released</th>
</tr>
#foreach ($films as $film)
<tr>
<td>
{{$film->title}}
</td>
<td>{{$film->director}}</td>
<td>{{$film->description}}</td>
<td>{{ Carbon\Carbon::parse($film->date)->format('l\\, jS \\of F Y\\, h:i A') }}</td>
</tr>
#endforeach
</body>
</html>
Comments view
<h1>{{ $film->title }}</h1>
<!--<p>{{$film->comments}}</p>-->
<table id="myTable">
<tr>
<th>Comment</th>
<th>User</th>
<th>Update</th>
<th>Delete</th>
#foreach ($film->comments as $comment)
<tr>
<td>{{$comment->body}}</td>
<td>Lorem</td>
<td>Update</td>
<td>Delete</td>
</tr>
#endforeach
</table>
<div>#include('form')</div>
The home controller and views remain as the were created by make:auth...
Home view
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Dashboard</div>
<div class="panel-body">
#if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
#endif
You are logged in!
</div>
</div>
</div>
</div>
</div>
#endsection
Home controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('home');
}
}
Film Controller function which relates to displaying comments:
/* Displays comments for a film*/
public function comment($id)
{
$film = Film::find($id);
return view('comment', compact('film'));
}
All my other code works apart from this. I am getting this error when I just click the login/register link. I don't see the page content at all. It takes you straight to the object error.

The error is caused by this line:
<h1>{{ $film->title }}</h1>
You need to return $film with the Film object in it from the controller method that renders comments view. For example:
return view('comments', ['film' => Film::find(1)]);
Also, put these route at the end of the web.php file:
Route::get('/{id}', 'FilmsController#comment');
Route::post('/{id}', 'FilmsController#addComment')->name('addComment');

Related

Laravel Backpack file upload

I recently installed laravel backpack
And my form has a pdf file to upload
I read the tutorial on backpack but was unable to solve it
I Debugged and found that
request()->hasFile() is empty
no file in request
and html code of the add form has no enctype="" in it
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\FileUploadController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('file-upload', [FileUploadController::class, 'fileUpload'])->name('file.upload');
Route::post('file-upload', [FileUploadController::class, 'fileUploadPost'])->name('file.upload.post');
Create FileUploadController
app/Http/Controllers/FileUploadController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class FileUploadController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function fileUpload()
{
return view('fileUpload');
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function fileUploadPost(Request $request)
{
$request->validate([
'file' => 'required|mimes:pdf,xlx,csv|max:2048',
]);
$fileName = time().'.'.$request->file->extension();
$request->file->move(public_path('uploads'), $fileName);
return back()
->with('success','You have successfully upload file.')
->with('file',$fileName);
}
}
Create Blade File
resources/views/fileUpload.blade.php
<!DOCTYPE html>
<html>
<head>
<title>laravel 8 file upload example - ItSolutionStuff.com.com</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="panel panel-primary">
<div class="panel-heading"><h2>laravel 8 file upload example - ItSolutionStuff.com.com</h2></div>
<div class="panel-body">
#if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>{{ $message }}</strong>
</div>
#endif
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="{{ route('file.upload.post') }}" method="POST" enctype="multipart/form-data">
#csrf
<div class="row">
<div class="col-md-6">
<input type="file" name="file" class="form-control">
</div>
<div class="col-md-6">
<button type="submit" class="btn btn-success">Upload</button>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
Laravel Backpack is for admin CRUD functionalities. All you need to do in the admin controller is to define the field type as "Browse" for file upload. Example, below is to upload and file. It will upload single file in your laravel default filesystem and save the path in photo_path field of database.
$this->crud->addField([ // Photo
'name' => 'photo_path',
'label' => "Photo",
'type' => 'browse'], 'both');
This is for the admin only, if you want upload feature for frontend, Backpack API's are not for that. In that case, check in Laravel docs.

Laravel: Login system problem for learning

I'm trying to make a login for learning, so I followed a video from youtube with the same coding. It should be able to check the format of the inputted data, check whether user already login or not, check whether user accessing the next page wihthout login, but in the end, it will always only showed email and password required errors even if I already inputted the right input. Please help. Here are my codes.
web.php
<?php
use Illuminate\Support\Facades\Route;
Route::get('/main', 'MainController#index');
Route::post('/main/checklogin', 'MainController#checklogin');
Route::get('main/successlogin', 'MainController#successlogin');
Route::get('main/logout', 'MainController#logout');
login.blade.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Login</title>
<!--CSS-->
<link rel="stylesheet" href="{{ asset('css/styles.css') }}" type="text/css">
<link rel="stylesheet" href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css' />
<script type="text/javascript" src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js'></script>
</head>
<body>
<div class="login-page-frame">
<div class="header-login-page-frame">
<h3>Login</h3>
</div>
<div class="inner-login-form-frame">
#if(isset(Auth::user()->email))
<script>window.location="/main/successlogin";</script>
#endif
#if($message = Session::get('error'))
<div class="alert alert-danger alert-block">
<button type="button" class="close" data-dismiss="alert"></button>
<strong>{{$message}}</strong>
</div>
#endif
#if(count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form method="post" action="{{ url('/main/checklogin') }}" class="login-form">
{{ csrf_field() }}
<input type="email" placeholder="email" name="login-email" class="form-control">
<br>
<input type="password" placeholder="pass" name="login-password" class="form-control">
<br>
<input type="submit" name="login" class="btn-login" value="login">
</form>
</div>
</div>
</body>
</html>
halamanUtama.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Halaman Utama</title>
</head>
<body>
<div class="container box">
<h3 align="center">Selamat Datang</h3>
<br />
#if(isset(Auth::user()->email))
<div class="alert alert-danger success-block">
<strong>Welcome {{ Auth::user()->email }}</strong>
<br />
Logout
</div>
else
<script>window.location="/main";</script>
#endif
</div>
</body>
</html>
MainController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator;
use Auth;
use Input;
class MainController extends Controller
{
//
function index(){
return view('login');
}
function checklogin(Request $request){
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|alphaNum|min:3'
]);
$user_data=array(
'email' => $request->get('login-email'),
'password' => $request->get('login-password')
);
if(Auth::attempt($user_data)){
return redirect('main/successlogin');
}else{
return back()->with('error', 'Wrong Login Details');
}
}
function successlogin(){
return view('halamanUtama');
}
function logout(){
Auth::logout();
return redirect('main');
}
}
I won't comment on whether any of your other code works, but the cause of your validation errors is that the name of your form inputs does not match the name of the fields you are trying to validate.
In your form, your inputs are called login-email and login-password. However, in your controller, you are validating that a field called email and a field called password are provided (because they are required).
So either change your form names to email and password or change your validation fields to login-email and login-password.

Laravel 5.8 image upload

After creating a Laravel site with user login, I wanted to add file upload ability. I followed a simple tutorial but when it came to do php artisan migrate it didn’t work because Base table or view already exists so I created an images table manually in MySQL.
Finally, I navigated to my websites image upload page http://localhost/sites/mywebsite/public/image and attached an image. The error I got was The POST method is not supported for this route. Supported methods: GET, HEAD.
This is the line in my image.blade.php file:
<form action="{{ url('save') }}" method="post" accept-charset="utf-8" enctype="multipart/form-data">
Note; When I created an images table manually in MySQL I only added 'id' and 'image' columns and I wasn't 100% sure how to format them.
Any help very much appreciated.
Here's my ImageController
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator, Redirect, Response, File;
use App\Image;
class ImageController extends Controller
{
public function index()
{
return view('image');
}
public function save(Request $request)
{
request()->validate([
'image' => 'required',
'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
if ($image = $request->file('image')) {
foreach ($image as $files) {
$destinationPath = 'public/image/'; // upload path
$profileImage = date('YmdHis') . "." . $files->getClientOriginalExtension();
$files->move($destinationPath, $profileImage);
$insert[]['image'] = "$profileImage";
}
}
$check = Image::insert($insert);
return Redirect::to("image")->withSuccess('Great! Image has been successfully uploaded.');
}
}
Image.blade.php
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Laravel 5.7 Multiple Image Upload Example - Tutsmake.com</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
<style>
.container {
padding: 10%;
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<h2 style="margin-left: -48px;">Laravel 5.7 Multiple Image Upload Example - Tutsmake.com</h2>
<br>
<br>
#if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>{{ $message }}</strong>
</div>
<br>
#endif
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Opps!</strong> There were something went wrong with your input.
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
<br>
#endif
<form action="{{ url('save') }}" method="post" accept-charset="utf-8" enctype="multipart/form-data">
#csrf
<div class="avatar-upload col-6">
<div class=" form-group avatar-edit">
<input type='file' id="image" name="image[]" accept=".png, .jpg, .jpeg" />
<label for="imageUpload"></label>
</div>
</div>
<div class="form-group col-3">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</form>
</div>
</body>
</html>
Migration table
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateImagesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('images', function (Blueprint $table) {
$table->increments('id');
$table->increments('image');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('images');
}
}
Follow Any Method :
<form action="{{ url('save') }}" method="get" accept-charset="utf-8" enctype="multipart/form-data">
And Change Migartion $table->text('image');
OR
Route::post('save', 'ImageController#save');
And Change Migartion $table->text('image');
You need to create a POST method route in routes/web.php.
A get route does not support posting form data
Route::post('save', 'ImageController#save');
Also, the image column in your database should be a string, an integer can't hold a path to a file
$table->string('image');
But you can't insert an array to a string column anyway so you should move the Model create method inside the foreach loop
foreach ($image as $files) {
$destinationPath = 'public/image/'; // upload path
$profileImage = date('YmdHis') . "." . $files->getClientOriginalExtension();
$files->move($destinationPath, $profileImage);
Image::insert($profileImage);
}

Laravel - pagination with created_at pages sorting

So guys I'm working on this project and I need laravel pagination. I already tried laravel basic pagination with $posts->links() on my blade but it is not working. I think like there is some update on it or something. I need pagination to be paginate by created_at, so on one page it needs to show me all posts created at same day. Can you pls help me
Here is my HomeController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use App\Post;
use DB;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
$user_id = auth()->user()->id;
$user = User::find($user_id);
return view('home')->with('posts', $user->posts);
}
}
Here is my home.blade.php
#extends('layouts.theme')
#section('content')
<style>
body{
margin: 0;
background-color: #EBEBEB;
}
</style>
<div class="mainl">
<div class="row">
<div class="columna">
<h1>{{ Auth::user()->name }}</h1>
<hr>
</div>
<div class="columns">
<a href="{{ route('logout') }}" id="logout"
onclick="event.preventDefault();
document.getElementById('logout-form').submit();">
{{ __('LOGOUT') }}
</a>
<form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
#csrf
</form>
</div>
</div>
</br></br></br>
#if(count($posts)> 0)
<table>
<thead>
<tr>
<th>BR.KESICE</th>
<th>IME I PREZIME</th>
<th>BR.TELEFONA</th>
<th>POSAO</th>
<th>CIJENA</th>
<th>PLACANJE</th>
<th>POPUST</th>
<th>DATUM PREUZ.</th>
<th>DATUM IZDAV.</th>
<th>SMJENA</th>
<th>RADNIK</th>
<th>STATUS</th>
<th>IZMIJENI</th>
</tr>
</thead>
<tbody>
#foreach($posts as $post)
<tr>
<td>{{$post->br_kesice}}</td>
<td>{{$post->ime}}</td>
<td>{{$post->br_telefona}}</td>
<td>{{$post->posao}}</td>
<td>{{$post->cijena}}</td>
<td>{{$post->placanje}}</td>
<td>{{$post->popust}}</td>
<td>{{$post->datum_preuz}}</td>
#if($post->status == 1)
<td>/</td>
#else
<td>{{$post->datum_izdav}}</td>
#endif
<td>{{$post->smjena}}</td>
<td>{{$post->radnik}}</td>
<td>
#if($post->status == 0)
<span class="label label-primary" id="statusdeaktivan">Deaktivan</span>
#elseif($post->status == 1)
<span class="label label-success" id="statusaktivan">Aktivan</span>
#elseif($post->status == 2)
<span class="label label-danger" id="statusdeaktivan">Rejected</span>
#else
<span class="label label-info" id="statusdeaktivan">Deaktivan</span>
#endif
</td>
#if($post->status == 3)
#else
<td><i class="far fa-edit"></i></td>
#endif
</tr>
#endforeach
</tbody>
<tfoot>
<tr>
<th>UKUPAN IZNOS: {{ Auth::user()->posts->sum('cijena')}}€</th>
<th>KARTICA: {{ Auth::user()->posts->where('placanje', 'Kartica')->sum('cijena')}}€</th>
<th>GOTOVINA: {{ Auth::user()->posts->where('placanje', 'Gotovina')->sum('cijena')}}€</th>
<th>VIRMAN: {{ Auth::user()->posts->where('placanje', 'Virman')->sum('cijena')}}€</th>
</tr>
</tfoot>
</table>
#else
<p>Trenutno nema unosa.</p>
#endif
</div>
#endsection
if you need anything else to help, please comment and I will add it.
It is because you're not getting your posts paginated, but all of them.
You just need to change $user->posts to $user->posts()->paginate() for it to work. Optionally, you may pass a number to the paginate method to tell it how many records per page do you need.
Hope it helps!

NotFoundHttpException in Handler.php line 131:

I know this is probably something really stupid but I just can't seem to fix it.
I'm getting this error
NotFoundHttpException in Handler.php line 131: No query results for model [App\Modules\Menus\Models\Menu].
And can't seem to fix it. At the moment it shouldn't even be asking for the Menu model.
Here is my route.php
Route::get('/signup', [
'uses' => 'OpenController#signup',
'as' => 'signup'
]);
Here is my OpenController.php
<?php
namespace App\Modules\Open\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Modules\Menus\Models\Menu;
use App\Modules\Authors\Models\Story;
class OpenController extends Controller
{
public function index(){
$menus_child = Menu::where('menu_id', 0)->with('menusP')->get();
$menu = Menu::where('id', 1)->orWhere('title', 'home')->firstOrFail();
return view('open::index', compact('menus_child', 'menu'));
}
public function content($id){
$menus_child = Menu::where('menu_id', 0)->with('menusP')->get();
$menu = Menu::where('id', $id)->firstOrFail();
$layout = $menu->type;
$stories = Story::where('type', 'public')->get();
return view('open::public/'.$layout, compact('menus_child', 'menu', 'stories'));
}
public function signup(){
echo "sign up";
die();
}
}
Here is my signup.blade.php
#extends('templates::layouts.public')
#section('content')
<h1>signup blade</h1>
#stop
Here is my public.blade.php layout
<!DOCTYPE html>
<html>
<head>
<title>Website</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://fonts.googleapis.com/css?family=Cherry+Swash|Crafty+Girls|Homemade+Apple|Italianno|Parisienne|Ranga|Rochester" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
{!! Html::style('css/bootstrap.min.css') !!}
{!! Html::style('css/style.css') !!}
{!! Html::script('js/jquery-3.1.1.min.js') !!}
{!! Html::script('js/bootstrap.min.js') !!}
{!! Html::script('js/main.js') !!}
</head>
<body>
<div class="container">
<div id="main">
<div id="header">
<div id="logo">
<div class="row">
<div class="col-lg-6">
<h1>Website</h1>
</div>
<div class="col-lg-6">
<div class="slogan">
{!! Html::link('/signup', 'Signup') !!} / {!! Html::link('/login', 'Login') !!}
</div>
</div>
</div>
</div>
#include('menus::menu')
</div>
<div id="site_content">
<div id="content">
#yield('content')
</div>
</div>
</div>
</div>
</body>
</html>
And this is my menu.blade.php
<div id="menubar">
<ul class="nav navbar-nav" id="menu">
#foreach($menus_child as $grandfather)
#if($grandfather->menu_id)
<li>
#elseif($grandfather->title == 'Home')
<li class="parent {{ menu_active([$grandfather->id]) }}">
#elseif(count($grandfather->menusP()->where('menu_id', '>', 0)->get()))
<li class="dropdown {{ menu_active([$grandfather->id]) }}">
#else
<li class="parent {{ menu_active([$grandfather->id]) }}">
#endif
#if(count($grandfather->menusP()->where('menu_id', '>', 0)->get()))
{!! HTML::decode(HTML::link($grandfather->id, $grandfather->title.'<span class="caret"></span>', array('class' => 'dropdown-toggle')))!!}
#else
{!! HTML::link($grandfather->id, $grandfather->title) !!}
#endif
#if(count($grandfather->menusP))
<ul class="dropdown_menu">
#foreach($grandfather->menusP as $father)
#if($father->menu_id)
<li class="parent_child">
#else
<li>
#endif
{!! HTML::link($father->id, $father->title) !!}
#endforeach
</ul>
#endif
#endforeach
</ul>
</div>
I found out what caused the issue. It was how I had my routes placed. So all I did was put my signup route on top of my routes and that solved my problem
#Gus, #Isis
This post helped me solve a very similar (or possibly same) issue. In my particular case, I immediately realized it was simple user error - and this may help explain why this may happen...
Consider visiting the following URL given the subsequent routes:
GET app.com/team/add-favorite
[bad] Routes:
// Bad Routing Logic
Route::get('/team/{team}', 'TeamController#show');
Route::get('/team/add-favorite', 'UserTeamController#default');
Route::get('/team/add-favorite/{conference}', 'UserTeamController#index');
Obviously, the 2nd route ( /team/add-favorite ) will never be called because it's simply going to route to /team/{team} with the [team] parameter filled with a value of "add-favorite".
My solution was to also simply re-arrange the order of the routes, like so...
[better] Routes:
// Still not good practice, but works
Route::get('/team/add-favorite', 'UserTeamController#default');
Route::get('/team/add-favorite/{conference}', 'UserTeamController#index');
Route::get('/team/{team}', 'TeamController#show');
This is still definitely not best practice, but will at least allow each of the routes to resolve properly.
app.com/team/add-favorite will now match the first route, while something like app.com/team/17 will still fall to the 3rd listed route and be handed to the TeamController with an appropriate ID.
Again - I don't recommend routing this way with "shared" endpoints as it could definitely still cause problems. i.e - better hope there were never a team with and ID = 'add-favorite'. Highly improbable, but you get the point...
Hope this helps!

Resources