How can I post several images from this Controller? - php

Basic Information
I'm developing a simple Web Application that it can post photo using Laravel.
My Question
I want to create several image post form using another variable.
How can I make work my Controllers using another variable?
My Codes
routes/web.php
<?php
/*
|--------------------------------------------------------------------------
| 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('login');
Route::group(['middleweare' => 'auth'], function () {
Route::get('/', 'StoriesController#index');
Route::post('/', 'StoriesController#store');
Route::get('/stories/create', 'StoriesController#add');
Route::post('/stories/create', 'StoriesController#uplaod');
});
Route::group(['middleweare' => 'auth','name'=>'profile'], function () {
Route::get('/profile/edit', 'ProfileController#edit');
Route::get('/profile/create', 'ProfileController#add');
Route::post('/profile/create', 'ProfileController#store');
Route::post('/profile/create', 'ProfileController#upload');
});
Route::get('/home', 'HomeController#index')->name('home');
Auth::routes();
app/Http/Controllers/StoriesController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Story;
use Auth;
use App\Posts;
use App\History;
use App\Attachment;
use Carbon\Carbon;
use Storage;
class StoriesController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index(Request $request)
{
$images = Attachment::all();
return view('stories.index2', compact('images'));
}
public function add()
{
return view('stories.create2');
}
public function store(Request $request)
{
$d = new \DateTime();
$d->setTimeZone(new \DateTimeZone('Asia/Tokyo'));
$dir = $d->format('Y/m');
$path = sprintf('public/images/%s', $dir);
$data = $request->except('_token');
foreach ($data['images'] as $k => $v) {
$filename = '';
$attachments = Attachment::take(1)->orderBy('id', 'desc')->get();
foreach ($attachments as $attachment) {
$filename = $attachment->id + 1 . '_' . $v->getClientOriginalName();
}
unset($attachment);
if ($filename == false) {
$filename = 1 . '_' . $v->getClientOriginalName();
}
$v->storeAs($path, $filename);
$attachment_data = [
'path' => sprintf('images/%s/', $dir),
'name' => $filename
];
$a = new Attachment();
$a->fill($attachment_data)->save();
}
unset($k, $v);
return redirect('/');
}
public function upload(Request $request)
{
dd($request->all());
$this->validate($request, [
'file' => [
'required',
'file',
'image',
'mimes:jpeg,png',
]
]);
if ($request->file('file')->isValid([])) {
$path = $request->file->store('public');
return view('stories.index2')->with('filename', basename($path));
} else {
return redirect('/')
->back()
->withInput()
->withErrors();
}
}
}
I made a profile image post form, and general image post form.
And I want to view those image on same page.

Related

Bad routes for admin in Laravel

I am a newbie in Laravel and wanna create Admin Login and Registration. I have user registration and it works properly.
My web.php
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| 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::view('/', 'index');
Route::name('user.')->group(function () {
Route::view('/private', 'private')->middleware('auth')->name('private');
Route::get('/login', function() {
if (Auth::check()) {
return redirect(route('user.private'));
}
return view('login');
})->name('login');
Route::post('/login', [\App\Http\Controllers\LoginController::class, 'login']);
Route::get('/logout', function () {
Auth::logout();
return redirect('/');
})->name('logout');
Route::get('/registration', function() {
if (Auth::check()) {
return redirect(route('user.private'));
}
return view('registration');
})->name('registration');
Route::post('/registration', [\App\Http\Controllers\RegisterController::class, 'save']);
});
Route::name('admin.')->group(function () {
Route::view('/adminPrivate', 'adminPrivate')->middleware('auth')->name('adminPrivate');
// dd(Route::view('/adminPrivate', 'adminPrivate')->middleware('auth')->name('private'));
Route::get('/adminLogin', function() {
if (Auth::guard('admin')->check()) {
return redirect(route('admin.adminPrivate'));
}
return view('adminLogin');
})->name('login');
Route::post('/adminLogin', [\App\Http\Controllers\LoginAdminController::class, 'login']);
Route::get('/adminLogout', function () {
Auth::guard('admin')->logout();
return redirect('/');
})->name('logout');
Route::get('/adminRegistration', function() {
if (Auth::guard('admin')->check()) {
return redirect(route('admin.adminPrivate'));
}
return view('adminRegistration');
})->name('registration');
Route::post('/adminRegistration', [\App\Http\Controllers\RegisterAdminController::class, 'save']);
});
My RegisterAdminController.php
<?php
namespace App\Http\Controllers;
use App\Models\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class RegisterAdminController extends Controller
{
public function save(Request $request) {
if (Auth::guard('admin')->check()) {
return redirect(route('admin.adminPrivate'));
}
$validateFields = $request->validate([
'username' => 'required',
'password' => 'required'
]);
if (Admin::where('username', $validateFields['username'])->exists()) {
return redirect(route('admin.registration'))->withErrors([
'username' => 'Username already registered!'
]);
}
$admin = Admin::create($validateFields);
if ($admin) {
Auth::guard('admin')->login($admin);
return redirect(route('admin.adminPrivate'));
}
return redirect(route('admin.login'))->withErrors([
'formError' => 'Cannot save admin!'
]);
}
}
My LoginAdminController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
class LoginAdminController extends Controller
{
public function login(Request $request) {
if (Auth::guard('admin')->check()) {
return Redirect::to(route('admin.adminPrivate'));
}
$formFields = $request->only(['username', 'password']);
if (Auth::guard('admin')->attempt($formFields)) {
return Redirect::to(route('admin.adminPrivate'));
}
return redirect(route('admin.login'))->withErrors([
'username' => 'Can not authorize'
]);
}
}
I don't understand how I can solve this problem. Need a help. I tried modify all names of my Routes, but this didn't help.

How to make dynamic routes PHP MVC

How do I make a route for /blog/* where * is a slug for a blog post?
I am making a PHP MVC Framework from scratch and I'm making trouble with the showing data in view and how to make so people can click on blog posts to view it!
Please see the github: https://github.com/fillemon10/cinemania-mvc to understand and help me.
I dont know how do deal with retrieving data from database to blog.
index.php:
<?php
use app\controllers\AuthController;
use app\controllers\BlogController;
use app\controllers\SiteController;
use app\core\Application;
use app\models\Blog;
require_once __DIR__ . '/../vendor/autoload.php';
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();
$config = [
'userClass' => \app\models\User::class,
'db' => [
'dsn' => $_ENV['DB_DSN'],
'user' => $_ENV['DB_USER'],
'password' => $_ENV['DB_PASSWORD']
]
];
$app = new Application(dirname(__DIR__), $config);
$app->on(Application::EVENT_BEFORE_REQUEST, function () {
});
$app->router->get('/', [SiteController::class, 'home']);
$app->router->get('/contact', [SiteController::class, 'contact']);
$app->router->post('/contact', [SiteController::class, 'contact']);
$app->router->get('/login', [AuthController::class, 'login']);
$app->router->post('/login', [AuthController::class, 'login']);
$app->router->get('/register', [AuthController::class, 'register']);
$app->router->post('/register', [AuthController::class, 'register']);
$app->router->get('/logout', [AuthController::class, 'logout']);
$app->router->get('/myaccount', [AuthController::class, 'myaccount']);
$app->router->get('/blog', [BlogController::class, 'blog']);
$app->run();
router.php:
<?php
namespace app\core;
use app\core\exception\NotFoundException;
class Router
{
public Request $request;
public Response $response;
protected array $routes = [];
public function __construct(Request $request, Response $response)
{
$this->request = $request;
$this->response = $response;
}
public function get($url, $callback, $params ="")
{
$this->routes['get'][$url] = $callback;
}
public function post($url, $callback)
{
$this->routes['post'][$url] = $callback;
}
public function resolve()
{
$url = $this->request->getUrl();
$method = $this->request->method();
$callback = $this->routes[$method][$url] ?? false;
if ($callback === false) {
throw new NotFoundException();
}
if (is_string($callback)) {
return Application::$app->view->renderView($callback);
}
if (is_array($callback)) {
/** #var \app\core\Controller $controller */
$controller = new $callback[0]();
Application::$app->controller = $controller;
$controller->action = $callback[1];
$callback[0] = $controller;
foreach ($controller->getMiddlewares() as $middleware) {
$middleware->execute();
}
}
return call_user_func($callback, $this->request, $this->response);
}
}

Trying to get property 'id' of non-object-Laravel5-ConversationsController.php

hello everyone I have a big problem in the show function. I do not know what the problem is .. I get this error "Trying to get property 'id' of non-object"
ConversationController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use Illuminate\Support\Facades\Auth;
use App\Repository\ConversationRepository;
use Illuminate\Auth\AuthManager;
class ConversationsController extends Controller
{
private $r;
private $auth;
public function __construct(ConversationRepository $conversationRepository, AuthManager $auth){
$this->r= $conversationRepository;
$this->auth=$auth;
}
public function index () {
return view('conversations/index' , ['users'=> $this->r->getConversations($this->auth->user()->id)]);
}
public function show (User $user) {
return view('conversations/show',[
'users'=> $this->r->getConversations($this->auth->user()->id),
'user' => $user
]) ;
}
public function store(User $user){
$this->r->createMessage(
$request->get('content'),
$this->auth->user()->id,
$user->id
);
return redirect(route('conversations.show', ['id'=> $user->id]));
}
}
?>
web.php
<?php
//use Illuminate\Routing\Route;
//use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| 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('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'ConversationsController#index')->name('home');
Route::get('/conversations', 'ConversationsController#index')->name('conversations');
Route::get('/conversations/{user}', 'ConversationsController#show')->name('conversations.show');
Route::post('/conversations/{user}', 'ConversationsController#store');
enter image description hereConversationRepository.php
<?php
namespace App\Repository;
use App\User;
use App\Message;
class ConversationRepository {
private $user;
private $message;
public function __construct(User $user, Message $message){
$this ->user = $user;
$this->message= $message;
}
public function getConversations(int $userId){
return $this->user->newQuery()
->select('name', 'id')
->where('id', '!=', $userId)
->get();
}
public function createMessage (string $content, int $from, int $to){
return $this->message->newQuery()-> create([
'content' => $content,
'from_id' => $from,
'to' => $to,
'created_at' => Carbon::now()
]);
}
}
?>
the problem in this function
public function show (User $user) {
return view('conversations/show',[
'users'=> $this->r->getConversations($this->auth->user()->id),
'user' => $user
]) ;
more precisely in this line
'users'=> $this->r->getConversations($this->auth->user()->id)
And thanks ..
Try using $this->auth()->user()->id instead. Also the routes accessing auth should be enclosed within the web middleware.

NotWritableException Can't write image data to path

How to store an avatar correctly
(in developer mode) The way I have my Controller now
it stores the new image path to the database but doesn't upload it to the 'uploads/avatars' folder.
Also when I try to just edit the profile without uploading a new avatar, it throws an ErrorException undefined variable:avatar,
and the version i have on my hosting server also throws the Errorexception if not uploading but only editing the profile,
And if I try to upload a new avatar it tells me
NotWritableException
Can't write image data to path (/home/vlindr.com/vlindr/public/uploads/avatars/1504691841.jpg)
Anybody knows how to go about fixing this?
My Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use Auth;
use Session;
use Image;
use Illuminate\Support\Facades\File;
use App\User;
use DB;
use Illuminate\Support\Facades\Storage;
class UserController extends Controller
{
public function __construct()
{
$this->middleware('auth', ['except' => ['index', 'show']]);
}
//
public function index(){
return view('profiles.profile', array('user' => Auth::user()) );
}
public function edit()
{
return view('profiles.edit')->with('info', Auth::user()->profile);
}
public function update(Request $request)
{
$this->validate($request, [
'location' => 'required',
'about' => 'required|max:355',
'passion' => 'required|max:355'
]);
Auth::user()->profile()->update([
'location' => $request->location,
'about' => $request->about,
'passion' => $request->passion
]);
$user = User::find(Auth::user()->id);
// Handle the user upload of avatar
if ($request->hasFile('avatar')) {
$avatar = $request->file('avatar');
$filename = time() . '.' . $avatar->getClientOriginalExtension();
}
// Delete current image before uploading new image
if ($user->avatar !== 'man.png' && $user->avatar !== 'woman.png')
{
$file = public_path('/uploads/avatars/' . $user->avatar);
if (File::exists($file)) {
unlink($file);
}
}
Image::make($avatar->getRealPath())->resize(350, 350)->save( public_path('/uploads/avatars/' . $filename ) );
$user = Auth::user();
$user->avatar = $filename;
$user->save();
return back()->with('msg', 'Profiel is bijgewerkt');
}
}

Inputting to a Controllers closure in laravel 5.2

So i have a 'TicketController' which holds my functions for manipulating 'tickets' in a system.
I am looking to work out the best way to send my new route that will take a route parameter of {id} to my TicketController to view a ticket.
Here is my route set
Route::group(['middleware' => 'auth', 'prefix' => 'tickets'], function(){
Route::get('/', 'TicketController#userGetTicketsIndex');
Route::get('/new', function(){
return view('tickets.new');
});
Route::post('/new/post', 'TicketController#addNewTicket');
Route::get('/new/post', function(){
return view('tickets.new');
});
Route::get('/view/{id}', function($id){
// I would like to ideally call my TicketController here
});
});
Here is my ticket controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Ticket;
use App\User;
class TicketController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
/**
* Returns active tickets for the currently logged in user
* #return \Illuminate\Http\Response
*/
public function userGetTicketsIndex()
{
$currentuser = \Auth::id();
$tickets = Ticket::where('user_id', $currentuser)
->orderBy('updated_at', 'desc')
->paginate(10);
return view('tickets.index')->with('tickets', $tickets);
}
public function userGetTicketActiveAmount()
{
$currentuser = \Auth::id();
}
public function addNewTicket(Request $request)
{
$this->validate($request,[
'Subject' => 'required|max:255',
'Message' => 'required|max:1000',
]);
$currentuser = \Auth::id();
$ticket = new Ticket;
$ticket->user_id = $currentuser;
$ticket->subject = $request->Subject;
$ticket->comment = $request->Message;
$ticket->status = '1';
$ticket->save();
}
public function viewTicketDetails()
{
//retrieve ticket details here
{
}
You don't need to use closure here. Just call an action:
Route::get('/view/{id}', 'TicketController#showTicket');
And in TicketController you'll get ID:
public function showTicket($id)
{
dd($id);
}
More about this here.
You should use type-hint in laravel. Its awesome
In route
Route::get('/view/{ticket}', 'TicketController#viewTicketDetails');
In controller
public function viewTicketDetails(Ticket $ticket)
{
//$ticket is instance of Ticket Model with given ID
//And you don't need to $ticket = Ticket::find($id) anymore
{

Categories