i wanna update the data of categories on multilevel choose item, but i had a problem, i can edit the categories without choose a parent, but i can't edit the categories when i choose a parent. then its showing a error called undefined offset:1 and here the trace error
Illuminate\Foundation\Bootstrap\HandleExceptions::handleError
C:\laragon\www\oesingcoffee\vendor\laravel\framework\src\Illuminate\Validation\Concerns\ValidatesAttributes.php:874
this is validates attrib in laravel framework
protected function getExtraConditions(array $segments)
{
$extra = [];
$count = count($segments);
for ($i = 0; $i < $count; $i += 2) {
$extra[$segments[$i]] = $segments[$i + 1]; //this is the 874 line
}
return $extra;
}
this is the CategoryRequest class
class CategoryRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
$parentId = (int) $this->get('parent_id');
$id = (int) $this->get('id');
if($this->method() == 'PUT'){
if($parentId > 0){
$name = 'required|unique:categories,name,'.$id.'id,parent_id,'.$parentId;
}else{
$name = 'required|unique:categories,name,'.$id;
}
$slug = 'unique:categories,slug,'.$id;
}else{
$name = 'required|unique:categories,name,NULL,id,parent_id,'.$parentId;
$slug = 'unique:categories,slug';
}
return [
'name' => $name,
'slug' => $slug,
];
}
}
this is my controller to update the data
public function update(CategoryRequest $request, $id)
{
$params = $request->except('_token');
$params['slug'] = Str::slug($params['name']);
$params['parent_id'] = (int)$params['parent_id'];
$category = Category::findOrFail($id);
if ($category->update($params)) {
Session::flash('success', 'Category has been updated.');
}
return redirect('admin/categories');
}
this the view form
#extends('admin.layout')
#section('content')
#php
$formTitle = !empty($category) ? 'Update' : 'New'
#endphp
<div class="content">
<div class="row">
<div class="col-lg-6">
<div class="card card-default">
<div class="card-header card-header-border-bottom">
<h2>{{ $formTitle }} Category</h2>
</div>
<div class="card-body">
#include('admin.partials.flash', ['$errors' => $errors])
#if (!empty($category))
{!! Form::model($category, ['url' => ['admin/categories', $category->id], 'method' => 'PUT']) !!}
{!! Form::hidden('id') !!}
#else
{!! Form::open(['url' => 'admin/categories']) !!}
#endif
<div class="form-group">
{!! Form::label('name', 'Name') !!}
{!! Form::text('name', null, ['class' => 'form-control', 'placeholder' => 'category name']) !!}
</div>
<div class="form-group">
{!! Form::label('parent_id', 'Parent') !!}
{!! General::selectMultiLevel('parent_id', $categories, ['class' => 'form-control', 'selected' => !empty(old('parent_id')) ? old('parent_id') : !empty($category['parent_id']) ? $category['parent_id'] : '', 'placeholder' => '-- Choose Category --']) !!}
</div>
<div class="form-footer pt-5 border-top">
<button type="submit" class="btn btn-primary btn-default">Save</button>
Back
</div>
{!! Form::close() !!}
</div>
</div>
</div>
</div>
#endSection
this is the migration
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('slug');
$table->bigInteger('parent_id');
$table->timestamps();
});
}
this is the edit method in controller
public function edit($id)
{
$category = Category::findOrFail($id);
$categories = Category::orderBy('name', 'asc')->get();
$this->data['categories'] = $categories->toArray();
$this->data['category'] = $category;
return view('admin.categories.form', $this->data);
}
you should try save() method.
public function update(CategoryRequest $request, $id)
{
$params = $request->except('_token');
$params['slug'] = Str::slug($params['name']);
$params['parent_id'] = (int)$params['parent_id'];
$category = Category::findOrFail($id);
if ($category->save()) {
Session::flash('success', 'Category has been updated.');
}
return redirect('admin/categories');
}
Replace with above one.
public function update(CategoryRequest $request, $id)
{
$params = $request->except('_token');
$category = Category::findOrFail($id);
$category->slug = Str::slug($params['name']);
$category->parent_id = (int)$params['parent_id'];
$category->save();
Session::flash('success', 'Category has been updated.');
return redirect('admin/categories');
}
I think your issue is inyour validation rule (specifically in your unique rule). May I suggest something else ?
I don't have the environment to test it right but now, so it may have some tweak to do.
use Illuminate\Validation\Rule;
...
public function rules()
{
$name = [
'required',
Rule::unique('categories')->where(function ($query) {
return $query->where('name', $this->name)
->where('parent_id', $this->parent_id);
})->ignore($this->id, 'id'),
];
$slug = [
Rule::unique('categories', 'slug')->ignore($this->id, 'id'),
];
return [
'name' => $name,
'slug' => $slug,
];
}
Related
I am trying to save uploaded image to uploads folder as well as database at the time of user registration, the image name is successfully saved to the database along with user details like name, address, email and etc. I am new to laravel. Please can any one suggest me, thank you.
Please find below is my register.blade.php
#extends('layouts.site')
#section('content')
<div class="login-content">
<a class="hiddenanchor" id="signup">
</a>
<a class="hiddenanchor" id="signin">
</a>
#include('layouts.site-navigation')
#include('errors.errors')
<div class="login_wrapper">
<div class="animate form login_form">
<section class="login_content">
<!-- <form> -->
<h1>Registration Form
</h1>
{!! Form::open(array('url' => URL_USERS_REGISTER, 'method' => 'POST',
'name'=>'formLanguage ', 'novalidate'=>'', 'class'=>"loginform",
'name'=>"registrationForm", 'files'=>'true')) !!}
<div>
</div>
<div>
{{ Form::text('username', $value = null , $attributes =
array('class'=>'form-control',
'placeholder' => getPhrase("username"),
'ng-model'=>'username',
'required'=> 'true',
'ng-class'=>'{"has-error": registrationForm.username.$touched &&
registrationForm.username.$invalid}',
'ng-minlength' => '4',
)) }}
</div>
<div>
{{ Form::text('rollnumber', $value = null , $attributes =
array('class'=>'form-control',
'placeholder' => getPhrase("roll number"),
'ng-minlength' => '2',
)) }}
<div>
{{ Form::text('branch', $value = null , $attributes =
array('class'=>'form-control',
'placeholder' => getPhrase("branch"),
'ng-minlength' => '2',
)) }}
</div>
<div>
{{ Form::text('phone', $value = null , $attributes =
array('class'=>'form-control',
'placeholder' => getPhrase("phone"),
'ng-model'=>'phone',
'ng-pattern' => getRegexPattern('phone'),
'required'=> 'true',
'ng-class'=>'{"has-error": registrationForm.phone.$touched &&
registrationForm.phone.$invalid}',
'ng-minlength' => '10',
)) }}
</div>
<div>
<select id="make" name="place" class="form-control">
<option value="" disabled selected>Interested Work Place
</option>
<option value="Yemmiganur">Yemmiganur
</option>
<option value="Raichur">Raichur
</option>
</select>
</div>
<br>
<div>
Interested To Work In Night Shift:
<input type="radio" name="night_shift" value="Yes" > Yes
<input type="radio" name="night_shift" value="No"> No
</div>
<div class="clearfix">
</div>
<div class="separator">
<p class="change_link">New to site?
<a href="#signup" class="to_register"> Next
</a>
</p>
<div class="clearfix">
</div>
</div>
<br>
<a href="{{URL_USERS_LOGIN}}">
<p class="text-center">{{getPhrase('i_am_having_account')}}
</p>
</a>
</div>
</section>
<div id="register" class="animate form registration_form">
<section class="login_content">
{!! Form::open(array('url' => URL_USERS_REGISTER, 'method' => 'POST',
'name'=>'formLanguage ', 'novalidate'=>'', 'class'=>"loginform",
'name'=>"registrationForm")) !!}
<!-- <form> -->
<h1>Registration Form
</h1>
<div>
{{ Form::email('email', $value = null , $attributes =
array('class'=>'form-control formclass',
'placeholder' => getPhrase("email"),
'ng-model'=>'email',
'required'=> 'true',
'ng-class'=>'{"has-error": registrationForm.email.$touched &&
registrationForm.email.$invalid}',
)) }}
</div>
<div>
{{ Form::password('password', $attributes = array('class'=>'form-
control formclass instruction-call',
'placeholder' => getPhrase("password"),
'ng-model'=>'registration.password',
'required'=> 'true',
'ng-class'=>'{"has-error": registrationForm.password.$touched &&
registrationForm.password.$invalid}',
'ng-minlength' => 5
)) }}
</div>
<div>
{{ Form::password('password_confirmation', $attributes =
array('class'=>'form-control formclass instruction-call',
'placeholder' => getPhrase("password_confirmation"),
'ng-model'=>'registration.password_confirmation',
'required'=> 'true',
'ng-class'=>'{"has-error":
registrationForm.password_confirmation.$touched &&
registrationForm.password_confirmation.$invalid}',
'ng-minlength' => 5,
'compare-to' =>"registration.password"
)) }}
{{ Form::text('aadhar_number', $value = null , $attributes =
array('class'=>'form-control',
'placeholder' => "UID (Aadhaar)",
'required'=> 'true',
'ng-class'=>'{"has-error": registrationForm.aadhar_number.$touched
&& registrationForm.aadhar_number.$invalid}',
'ng-minlength' => '12',
)) }}
<br>
</div>
<fieldset class="form-group" >
<input type="file" class="form-control" name="image"
accept=".png,.jpg,.jpeg" id="image_input">
</fieldset>
<?php $parent_module = getSetting('parent', 'module'); ?>
#if(!$parent_module)
<input type="hidden" name="is_student" value="0">
#else
<div class="row">
<div class="col-md-6">
{{ Form::radio('is_student', 0, true, array('id'=>'free')) }}
<label for="free">
<span class="fa-stack radio-button">
<i class="mdi mdi-check active">
</i>
</span> {{getPhrase('i_am_an_admin')}}
</label>
</div>
<div class="col-md-6">
{{ Form::radio('is_student', 0, true, array('id'=>'free')) }}
<label for="free">
<span class="fa-stack radio-button">
<i class="mdi mdi-check active">
</i>
</span> {{getPhrase('i_am_a_student')}}
</label>
</div>
</div>
#endif
<div class="text-center buttons">
<button type="submit" class="btn btn-default submit"
ng-disabled='!registrationForm.$valid'>
{{getPhrase('register_now')}}
</button>
</div>
{!! Form::close() !!}
<div class="clearfix">
</div>
<div class="separator">
<p class="change_link">Already a member ?
<a href="#signin" class="to_register"> Previous
</a>
</p>
<div class="clearfix">
</div>
</div>
</section>
</div>
</div>
#stop
#section('footer_scripts')
#include('common.validations')
#stop
AuthController.php
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use \Auth;
use Socialite;
use Exception;
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = '/';
protected $dbuser = '';
protected $provider = '';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'username' => 'required|max:255|unique:users',
// 'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'aadhar_number' => 'required|max:12|unique:users',
'password' => 'required|min:6|confirmed',
'image' => 'bail',
'place' => 'required',
'night_shift' => 'required',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data )
{
$type = 'student';
if($data['is_student'])
$type = 'parent';
$role = getRoleData($type);
$user = new User();
$user->username = $data['username'];
$user->rollnumber = $data['rollnumber'];
$user->branch = $data['branch'];
$user->email = $data['email'];
$user->password = bcrypt($data['password']);
$user->role_id = $role;
$user->image = $data['image'];
$user->place = $data['place'];
$user->night_shift = $data['night_shift'];
$user->phone = $data['phone'];
$user->aadhar_number = $data['aadhar_number'];
$user->slug = $user->makeSlug($user->username);
$user->save();
$user->roles()->attach($user->role_id);
try{
$this->sendPushNotification($user);
sendEmail('registration', array('user_name'=>$user->name,
'username'=>$data['username'], 'to_email' => $user->email,
'password'=>$data['password'], 'aadhar_number' => $user->aadhar_number));
}
catch(Exception $ex)
{
}
flash('success','record_added_successfully', 'success');
$options = array(
'name' => $user->name,
'image' => getProfilePath($user->image),
'slug' => $user->slug,
'role' => getRoleData($user->role_id),
);
pushNotification(['owner','admin'], 'newUser', $options);
return $user;
}
public function sendPushNotification($user)
{
if(getSetting('push_notifications', 'module')) {
if(getSetting('default', 'push_notifications')=='pusher') {
$options = array(
'name' => $user->name,
'image' => getProfilePath($user->image),
'slug' => $user->slug,
'role' => getRoleData($user->role_id),
);
pushNotification(['owner','admin'], 'newUser', $options);
}
else {
$this->sendOneSignalMessage('New Registration');
}
}
}
/**
* This is method is override from Authenticate Users class
* This validates the user with username or email with the sent password
* #param Request $request [description]
* #return [type] [description]
*/
protected function processUpload(Request $request, User $user)
{
if(env('DEMO_MODE')) {
return 'demo';
}
if ($request->hasFile('image')) {
$imageObject = new ImageSettings();
$destinationPath = $imageObject->getProfilePicsPath();
$destinationPathThumb = $imageObject->getProfilePicsThumbnailpath();
$fileName = $user->id.'.'.$request->image->guessClientExtension();
;
$request->file('image')->move($destinationPath, $fileName);
$user->image = $fileName;
Image::make($destinationPath.$fileName)->fit($imageObject-
>getProfilePicSize())->save($destinationPath.$fileName);
Image::make($destinationPath.$fileName)->fit($imageObject-
>getThumbnailSize())->save($destinationPathThumb.$fileName);
$user->save();
}
}
public function postLogin(Request $request)
{
$login_status = FALSE;
if (Auth::attempt(['aadhar_number' => $request->email, 'password' =>
$request->password])) {
// return redirect(PREFIX);
$login_status = TRUE;
}
elseif (Auth::attempt(['email'=> $request->email, 'password' =>
$request->password])) {
$login_status = TRUE;
}
if(!$login_status)
{
return redirect()->back()
->withInput($request->only($this->loginUsername(), 'remember'))
->withErrors([
$this->loginUsername() => $this->getFailedLoginMessage(),
]);
}
/**
* Check if the logged in user is parent or student
* if parent check if admin enabled the parent module
* if not enabled show the message to user and logout the user
*/
if($login_status) {
if(checkRole(getUserGrade(7))) {
if(!getSetting('parent', 'module')) {
return redirect(URL_PARENT_LOGOUT);
}
}
}
/**
* The logged in user is student/admin/owner
*/
if($login_status)
{
return redirect(PREFIX);
}
}
/**
* Redirect the user to the GitHub authentication page.
*
* #return Response
*/
public function redirectToProvider($logintype)
{
if(!getSetting($logintype.'_login', 'module'))
{
flash('Ooops..!', $logintype.'_login_is_disabled','error');
return redirect(PREFIX);
}
$this->provider = $logintype;
return Socialite::driver($this->provider)->redirect();
}
/**
* Obtain the user information from GitHub.
*
* #return Response
*/
public function handleProviderCallback($logintype)
{
try{
$user = Socialite::driver($logintype);
if(!$user)
{
return redirect(PREFIX);
}
$user = $user->user();
if($user)
{
if($this->checkIsUserAvailable($user)) {
Auth::login($this->dbuser, true);
flash('Success...!', 'log_in_success', 'success');
return redirect(PREFIX);
}
flash('Ooops...!', 'faiiled_to_login', 'error');
return redirect(PREFIX);
}
}
catch (Exception $ex)
{
return redirect(PREFIX);
}
}
public function checkIsUserAvailable($user)
{
$id = $user->getId();
$nickname = $user->getNickname();
$name = $user->getName();
$email = $user->getEmail();
$avatar = $user->getAvatar();
$this->dbuser = User::where('email', '=',$email)->first();
if($this->dbuser) {
//User already available return true
return TRUE;
}
$newUser = array(
'name' => $name,
'email'=>$email,
);
$newUser = (object)$newUser;
$userObj = new User();
$this->dbuser = $userObj->registerWithSocialLogin($newUser);
$this->dbuser = User::where('slug','=',$this->dbuser->slug)->first();
// $this->sendPushNotification($this->dbuser);
return TRUE;
}
public function socialLoginCancelled(Request $request)
{
return redirect(PREFIX);
}
}
First, you should urgently consider updating Laravel to newer versions.
Second, I think you are missing enctype="multipart/form-data" accept-charset="UTF-8" in your form tag
I'm trying to add a delete functionality into my project where the user can delete their status but I get the following error :
Screenshot of error
This is my HomeCotroller class:
namespace App\Http\Controllers;
use App\Eloquent\Status;
use App\Friends;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Laracasts\Flash\Flash;
//use Request;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\DB;
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(Request $request)
{
if (Input::has('like_status')) {
$status = Input::get('like_status');
$selectedStatus = Status::find($status);
$selectedStatus->likes()->create([
'user_id' => Auth::user()->id,
'status_id' => $status
]);
return redirect(route('home'));
}
if (Input::has('post_comment')) {
$status = Input::get('post_comment');
$commentBox = Input::get('comment-text');
$selectedStatus = Status::find($status);
$selectedStatus->comments()->create([
'comment_text' => $commentBox,
'user_id' => Auth::user()->id,
'status_id' => $status
]);
Flash::message('Your comment has been posted');
return redirect(route('home'));
}
if (Input::has('status-text')) {
$text = e(Input::get('status-text'));
$rules = [
'status-text' => 'required|string',
];
$vaildator = Validator::make($request->all(), $rules);
if (Input::hasFile('status_image_upload')) {
$file = Input::file('status_image_upload');
$mime = $file->getMimeType();
$image = $request->file('status_image_upload');
$imageName = str_random(8) . '_' . $image->getClientOriginalName();
//$imageFull = str_random(8).'_'.$image->getClientOriginalExtension();
$userStatus = new Status();
$userStatus->status_text = $text;
$userStatus->image_url = $imageName;
$userStatus->type = 1;
$userStatus->user_id = Auth::user()->id;
if ($mime == "video/x-flv" || $mime == "video/mp4" || $mime == "application/x-mpegURL" || $mime == "video/MP2T" || $mime == "video/3gpp" || $mime == "video/quicktime" || $mime == "video/x-msvideo" || $mime == "video/x-ms-wmv") {//process upload}
$vaildator = Validator::make($request->all(), $rules);
if (!$vaildator->fails()) {
$image->move('status_videos', $imageName);
$userStatus->type = 2;
$userStatus->save();
Flash::success('Your status has been posted');
return redirect(route('home'));
} else {
return back()->with('error', 'Validation failed:' . $vaildator->errors);
}
} else {
$rules['status_image_upload'] = 'image';
$vaildator = Validator::make($request->all(), $rules);
if (!$vaildator->fails()) {
$image->move('status_images', $imageName);
$userStatus->type = 1;
$userStatus->save();
Flash::success('Your status has been posted');
return redirect(route('home'));
} else {
return back()->with('error', 'Validation failed:' . $vaildator->errors);
}
}
} else {
}
if (!$vaildator->fails()) {
$userStatus = new Status();
$userStatus->status_text = $text;
$userStatus->user_id = Auth::user()->id;
$userStatus->save();
Flash::success('Your status has been posted');
return redirect(route('home'));
} else {
return back()->with('error', 'Validation failed:' . $vaildator->errors);
}
}
//Get top 15 post
$user_id = Auth::id();
$all_friends = Friends::where(['friend_id' => $user_id, 'status' => 1])
->orWhere(['user_id' => $user_id, 'status' => 1])
->get();
$friends = [];
foreach ($all_friends as $val) {
array_push($friends, $val->user_id, $val->friend_id);
}
$unique_friends = array_unique($friends);
if (!empty($unique_friends)) {
$top_15_posts = Status::whereIn('user_id', $unique_friends)
->orderBy('id', 'DESC')
->take(15)
->get();
} else {
$top_15_posts = Status::where('user_id', $user_id)
->orderBy('id', 'DESC')
->take(15)
->get();
}
//Get available friend request
$user_id = Auth::id();
$available_req_count = Friends::where(['friend_id' => $user_id, 'status' => 0])
->orderBy('id', 'desc')
->get()
->count();
return view('home', [
'top_15_posts' => $top_15_posts,
'available_req_count' => $available_req_count
]);
}
public function destroy($status_id)
{
$status =Status::where('id',$status_id)->first();
$status->delete();
return redirect()->route('home')->with(['message' => 'Successfully deleted!']);
}
}
This is user-status-layout.blade
<div class="panel panel-default">
<div class="panel-heading">{{$user->name}} - {{$status->created_at->diffForHumans()}} </div>
<div class="panel-body">
<div class="row">
<div class="col-md-1">
<img src="{{$user->getAvatar()}}" class="img-responsive">
</div>
<div class="col-md-11">
<p>{{$status->status_text}}</p>
#if($status->type == 1)
<img src="{{asset('status_images/'.$status->image_url)}}" class="img-responsive" style="width: 100%;">
#endif
</div>
<div class="col-md-12">
<hr>
<ul class="list-unstyled list-inline">
<li>
<button class="btn btn-xs btn-info" type="button" data-toggle="collapse" data-target="#view-comments-{{$status->id}}" aria-expanded="false" aria-controls="view-comments-{{$status->id}}">
<i class="fa fa-comments-o"></i>View & Comment</button>
</li>
<li>
#if(\App\Eloquent\StatusLikes::where(['status_id'=>$status->id,'user_id'=>Auth::user()->id])->first())
#else
{!! Form::open() !!}
{!! Form::hidden('like_status',$status->id)!!}
<button type="submit" class="btn btn-info btn-xs">
<i class="fa fa-thumbs-up"></i>Like status
</button>
{!! Form::close ()!!}
</li>
<button type="submit" class="btn btn-danger">
Delete
</button>
#endif
<li>
{{$comment_count}} comments
</li>
<li>
{{$like_count}} likes
</li>
</ul>
</div>
</div>
<div class="panel-footer clearfix">
{!! Form::open() !!}
{!! Form::hidden('post_comment',$status->id) !!}
<div class="form-group">
<div class="input-group">
<input type="text" class="form-control" name="comment-text" id="comment-text" placeholder="Post a comment...">
<span class="input-group-btn">
<button class="btn btn-default" type="submit"><i class="fa fa-send"></i>Add</button>
</span>
</div>
</div>
{!! Form::close() !!}
<div class="collapse" id="view-comments-{{$status->id}}">
#if($comments->first())
#foreach($comments as $comment)
<div class="row">
<div class="col-md-1">
<img src="{{\App\Eloquent\User::find($comment->user_id)->getAvatar()}}" class="img-responsive">
</div>
<div class="col-md-11">
<ul class="list-inline list-unstyled">
<li>
{{\App\Eloquent\User::find($comment->user_id)->name}}
</li>
<li>
posted {{$comment->created_at->diffForHumans()}}
</li>
</ul>
<p> {{$comment->comment_text}}</p>
</div>
</div>
<hr>
#endforeach
#else
<p>This status contains no comments.</p>
#endif
</div>
</div>
</div>
</div>
web.php:
<?php
//use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| 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');
});
Route::get('/test', function () {
return Auth::user()->test();
});
Auth::routes();
Route::any('/home', 'HomeController#index')->name('home');
Route::group(['as' => 'user.'], function () {
Route::get('/front', function () {
return view('front');
});
Route::get('/settings', ['as' => 'settings', 'uses' => 'ProfileController#viewSettings']);
Route::post('/settings', ['as' => 'settings', 'uses' => 'ProfileController#saveSettings']);
Route::any('/profile/{userId}', ['as' => 'profile', 'uses' => 'ProfileController#viewProfile']);
Route::get('/search/{query?}', ['as' => 'search', 'uses' => 'SearchController#search']);
Route::get('users', function () {
return User::find(1)->toJson();
});
Route::get('/chat', function () {
return view('chat');
});
Route::get('/calendar', function () {
return view('calendar');
});
Route::resource('events', 'EventsController', ['only' => ['index', 'store', 'update', 'destroy']]);
//Friends route
Route::post('/friends/request', ['as' => 'friends', 'uses' => 'FriendsController#sendRequest']);
Route::get('/friends/viewReq', ['as' => 'friends', 'uses' => 'FriendsController#viewFriendReq']);
Route::post('/friends/reqAction', ['as' => 'friends', 'uses' => 'FriendsController#requestAction']);
// Route::get('/status-delete/{status_id}',['uses' => 'HomeController#getDeleteStatus', 'as'=> 'user.status.delete',
// 'middleware' =>'auth'
// ]);
});
Also this what I get from php artisan route:list
Screenshot of routes
If you look at the name column in the route list, you'll see it is named user.status.delete not status.delete. This must mean your route group must have 'as' => 'user.' set which is going to prefix all routes in that group with user..
I have a form, I have troubles in Upload an Image :(
I am trying to upload some image and I don't know what I am doing bad :(
{{ Form::open (['route' => 'titulos.store', 'class'=> 'form', 'files'=> 'true']) }}
{{ Form::label('title', "Titulo:", ['class' => 'col-sm-2 control-label']) }}
{{ Form::text('title') }}
{{ $errors->first('title') }}
<div class="form-group">
{{ Form::label('date', "Fecha:", ['class' => 'col-sm-2 control-label']) }}
<input type="date" name="date" >
</div>
{{ Form::label('description', "Description:", ['class' => 'col-sm-2 control-label']) }}
{{ Form::textarea('description') }}
{{ $errors->first('description') }}
<div class="form-group">
{{ Form::file('image') }}
</div>
{{ Form::label('category_id', 'Category:', ['class' => 'col-sm-2 control-label']) }}
<div class="col-sm-10">
{{ Form::select('category_id', array('1' => 'TBLeaks', '2' => 'Quejas', '3' => 'Denuncias', '4' => 'Ideas'), null, array('class' => 'form-control')) }}
</div>
<div class="row">
<div class="col-sm-offset-2 col-sm-10">
{{ Form::submit('Submit', ['class' => "btn btn-primary"]) }}
</div>
</div>
<div class="row">
<div class="col-sm-offset-2 col-sm-10">
<a class="btn btn-success" href="{{ URL::to('admin') }}">Back to Admin</a>
</div>
</div>
{{ Form::close() }}
</div>
#if(Session::has('message'))
<div class="alert alert-{{ Session::get('class') }}">{{ Session::get('message')}}</div>
#endif
#stop
In my store function I have:
class TitulosController extends BaseController {
public function store(){
$rules = array(
'title' => 'required',
'description' => 'required',
'category_id' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
// proceso de valicion
if ($validator->fails()) {
return Redirect::to('titulos/create')
->withErrors($validator)
->withInput()->withErrors($validator);
} else {
//store
$image = Input::file('image');
$filename = $image->getClientOriginalName();
if(Input::hasFile('image')){
Input::file('image')->move(public_path().'/assets/img/', $filename);
}
$titulo = new Titulo();
$titulo->id = Input::get('id');
$titulo->title = Input::get('title');
$titulo->description = Input::get('description');
$titulo->date = Input::get('date');
$titulo->image = Input::$filename('image');
$titulo->category_id = Input::get('category_id');
$titulo->save();
return Redirect::to('titulos');
}
I have this model for the Titulo table:
class Titulo extends Eloquent {
use SoftDeletingTrait; // for soft delete
protected $dates = ['deleted_at']; // for soft delete
protected $table = 'titulos';
protected $primaryKey = 'id';
protected $fillable = array('image');
public $timestamps = true;
public function __construct() {
parent::__construct();
}
public function category(){
return $this->belongsTo('Category');
}
}
I have this for Image model:
class Image extends Eloquent {
public $timestamps = false;
protected $fillable = array('image');
}
At this line where your store to public path should be no problem
if(Input::hasFile('image')){
Input::file('image')->move(public_path().'/assets/img/', $filename);
}
Only your save Tutilo object looks not good. I think you have mistakenly add $ on Input::filename at this line. which will call the image
$titulo->image = Input::$filename('image');
change your code to this
$titulo = new Titulo();
$titulo->id = Input::get('id');
$titulo->title = Input::get('title');
$titulo->description = Input::get('description');
$titulo->date = Input::get('date');
$titulo->image = $filename; // I change this line. assuming you want to store the file name
$titulo->category_id = Input::get('category_id');
Here, I retrieve two tables to be displayed on one view page. The images are in the users table. When I clicked the profile tab, it displayed an error message:
Trying to get property of non-object.
What is wrong with my codes referring to the error message?
upload.blade.php
<div id="templatemo_sidebar">
<tr>
<div id="login">logged in as :</div>
</tr>
#foreach($users as $users)
<div id="img">
<img src="{!! '/profiles/'.$users->filePath !!}">{{$users->filePath}}
</div>
#endforeach
{!! Form::open(['action'=>'ProfileController#store', 'files'=>true]) !!}
<div class="form-group">
{!! Form::label('image', 'Choose an image') !!}
{!! Form::file('image') !!}
</div>
<div class="form-group">
{!! Form::submit('Save', array( 'class'=>'btn btn-danger form-control' )) !!}
</div>
{!! Form::close() !!}
#foreach($profiles as $profile)
<div id="profile_sidebar">
<tr>
<td>{{$profile->student_name}}</td>
</tr>
<tr>
<td>{{$profile->student_id}}</td>
</tr><br>
<tr>
<td>{{$profile->student_ic}}</td>
</tr>
<tr><br>
<td><mark>Status : {{$profile->status}}</mark></td>
</tr>
#endforeach
</div>
ProfileController.php
public function store(Request $request)
{
$users = Auth::user();
if($request->hasFile('image')) {
$file = Input::file('image');
//getting timestamp
//$timestamp = str_replace([' ', ':'], '-', Carbon::now()->toDateTimeString());
//$name = $timestamp. '-' .$file->getClientOriginalName();
$name=$file->getClientOriginalName();
$users->filePath = $name;
$file->move(public_path().'/profiles/', $name);
}
$users->save();
$users = Auth::user();
$users = Profile::where('student_id', $users->student_id)->get();
$profiles = Profile::all();
return view('profile', compact('users', 'profiles'));
}
}
Profile.php
class Profile extends Model
{
protected $table='profiles';
protected $fillable = ['student_id','student_name', 'program','faculty'];
public function user()
{
return $this->belongsTo('users');
}
public function setFirstNameAttribute($value) {
$this->attributes['faculty'] = ucfirst($value);
}
public function setLastNameAttribute($value) {
$this->attributes['program'] = ucfirst($value);
}
public function profilePicture(){
return $this->belongsTo('User', 'student_id');
}
}
In your first foreach you have to use a different variable for iterating through the users collection, like this:
#foreach($users as $user)
Just want to start by saying I have no clue what I'm doing...
I have a user_info table that looks like this
Schema::create('user_info', function(Blueprint $table){
$table->increments('id');
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
$table->string('address');
$table->string('city');
$table->string('state');
$table->string('zip');
$table->text('description');
$table->text('experience');
$table->timestamps();
});
I'm having trouble creating the update controller which looks like this right now.
public function update(Request $request)
{
$user = $request->user();
$data['description'] = $request->input('description');
$data['experience']=$request->input('experience');
$user->user_info -> $data->save();
}
again...no clue what I'm doing...
and this be my form:
<div class='col-md-10 well form-well'>
{!! Form::open(['method' => 'PATCH', 'action'=> ['UserController#update', Request::user()->id]]) !!}
<div class='row'>
<div class='form-group'>
<div class='col-md-2'>
{!! Form::label('description', 'About You')!!}
</div>
<div class='col-md-7'>
{!! Form::textarea('description', null, ['class'=>'form-control', 'rows'=>'3'])!!}
</div>
</div>
</div>
<div class='row'>
<div class='form-group'>
<div class='col-md-2'>
{!! Form::label('experience', 'Experience and Skills')!!}
</div>
<div class='col-md-7'>
{!! Form::text('experience', null, ['class'=>'form-control'])!!}
</div>
</div>
</div>
<div class='form-group'>
{!! Form::submit('Save Changes',['class'=> 'btn btn-md btn-success']) !!}
{!! Form::close()!!}
</div>
Update: I was able to update it like this:
$user->user_info->description = $data['description'];
$user->user_info->experience = $data['experience'];
$user->user_info->save();
But is there a way I can do something like :
$user->user_info->$request::Input::all();
$user->user_info->save();
Try this:
public function update(Request $request, $id)
{
$User = User::with('user_info')->find($id);
if(!$User) {
return response('User not found', 404);
}
$UserInfo = $User->user_info;
if(!$UserInfo) {
$UserInfo = new UserInfo();
$UserInfo->user_id = $id;
$UserInfo->save();
}
try {
$values = Input::only($UserInfo->getFillable());
$UserInfo->update($values);
} catch(Exception $ex) {
return response($ex->getMessage(), 400);
}
}
also in Your UserInfo model add this:
protected $fillable = array('description', 'experience');
public function getFillable() {
return $this->fillable;
}