Problem in showing user profile information in laravel 8 - php

I am having trouble showing user profile information in a profile page from the database which gives me Property [name] does not exist on this collection instance. (View: C:\xampp\htdocs\project_one\resources\views\profile.blade.php)
I have attached my code below
Route
Route::get('/profile', function() {
return view('profile', [
"title" => "Profile",
"profile" => Profile::all(),
"user" => User::all()
]);
});
Profile Table
public function up()
{
Schema::create('profiles', function (Blueprint $table) {
$table->id();
$table->string('name')->nullable();
$table->string('email')->unique();
$table->string('address')->nullable();
$table->string('phone')->nullable();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->timestamps();
});
}
Profile Model
class Profile extends Model
{
use HasFactory;
public function user(){
return $this->belongTo(User::class);
}
}
Function in User Model
public function profile(){
return $this->hasOne(Profile::class);
}
Blade template
<div class="form-group mb-3">
<label for="floatingName">Name</label>
<p>{{ $user->name }}</p>
</div>

your user query "user" => User::all() you are passing to the profile page is the whole users in you DB which is a collection of many users you can't get a specific user name with that......if you want the name of the currently logged in user you will have to use
<div class="form-group mb-3">
<label for="floatingName">Name</label>
<p>{{ auth()->user()->name }}</p>
</div>
without passing the user collection from your route.
or you can also pass the user logged in user through your route with this
Route::get('/profile', function() {
return view('profile', [
"title" => "Profile",
"profile" => Profile::all(),
"user" => auth()->user(),
]);
});
and in your view
<div class="form-group mb-3">
<label for="floatingName">Name</label>
<p>{{ $user->name }}</p>
</div>

Route::get('/profile', function() {
return view('profile', [
"title" => "Profile",
"profile" => Profile::all(),
"user" => User::all() // HERE IS THE PROBLEM
]);
});
User:all() returns collection of all users from the Database, For your case to get specific user on session use auth()->user()
Your Route should look like this
Route::get('/profile', function() {
return view('profile', [
"title" => "Profile",
"profile" => Profile::all(),
"user" => auth()->user(), // HERE IS THE SOLUTION
]);
});
Then you can use variable $user in a blade and get name of specific user
<div class="form-group mb-3">
<label for="floatingName">Name</label>
<p>{{ $user->name }}</p>
</div>

Related

Attempt to read property "id" on null LARAVEL8

I'm new to laravel and I'm learning it from laracast.
Here is my problem, I'm creating a comment form and it's php code looks like this:
<section class="col-span-8 col-start-5 mt-10 space-y-6">
<!-- Post form -->
<form method="POST" action="/post/{{ $post->slug }}/comments" class="border border-gray-200 p-6 rounded-xl">
#csrf
<header class="flex items-center">
<img src="https://i.pravatar.cc/100?id={{ auth()->id() }}" alt="" width="40" height="40" class="rounded-full">
<h2 class="ml-3 ">Want to participate?</h2>
</header>
<div class="mt-6">
<textarea class="w-full text-sm focus:outline-none focus:ring"
name="body"
cols="30" rows="10"
placeholder="Quick,think of something to say!" ></textarea>
</div>
<div>
<button type="submit" class="bg-blue-500 text-white uppercase font-semi-bold text-xs py-2 px-10 rounded-2xl hover:bg-blue-600">Post</button>
</div>
this is the corresponding route:
Route::post('post/{post:slug}/comments',[PostCommentsController::class, 'store']);
Controller:, and I suspect there could be something wrong here 'user_id'=> request()->user()->id, and I tried numerous ways for this approach like auth()->id, Auth::user()->id
<?php
namespace App\Http\Controllers;
use App\Models\Post;
class PostCommentsController extends Controller
{
public function store(Post $post){
request()->validate([
'body'=>'required'
]);
$post->comments()->create([
'user_id'=> request()->user()->id,
'body' => request('body')
]);
return back();
}
}
and this the migration table for comment
Schema::create('comments', function (Blueprint $table) {
$table->id();
$table->foreignId('post_id')->constrained()->cascadeOnDelete();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->text('body');
$table->timestamps();
migration table for post:
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->foreignId('category_id');
$table->string('slug')->unique();
$table->string('title');
$table->text('excerpt');
$table->text('body');
$table->timestamps();
$table->timestamp('published_at')->nullable();
});
If I click on post button I get the above error,tried my best to solve this problem but I couldn't. Can someone help me what's wrong with my code ?. My question may look naive as I'm new to stackoverflow community
use this code for controller
class PostCommentsController extends Controller
{
public function store(Post $post){
request()->validate([
'body'=>'required'
]);
$post->comments()->create([
'user_id'=> optional(auth()->user())->id,
'body' => request('body')
]);
return back();
}
}
user must logged in
first you must logged in
and in your route you must define your middleware if you are trying to get authenticated user's id like this
Route::post('post/{post:slug}/comments',[PostCommentsController::class, 'store'])->middleware('auth');
after that in your method/function inside controller use 'Request' class(not model class name) when you try to retrieve input from form
Laravel's 'Illuminate\Http\Request' class provides an object-oriented way to interact with the current HTTP request being handled by your application as well as retrieve the input, cookies, and files that were submitted with the request.
<?php
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Request; //don't forget this
class PostCommentsController extends Controller
{
public function store(Request $request){
request()->validate([
'body'=>'required'
]);
$post->comments()->create([
'user_id'=> auth()->user()->id,
'body' => request('body')
]);
return back();
}
}

Attempt to read property "alamat" on null - Laravel

hello I have 2 databases, namely users and profiles, profiles has a foreign key that is user_id. Then the relationship between the two is one to one.
Users migration
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Profiles migration
Schema::create('profiles', function (Blueprint $table) {
$table->id();
$table->string('alamat')->nullable();
$table->string('nip')->nullable();
$table->string('jabatan')->nullable();
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
User Model
use HasApiTokens, HasFactory, Notifiable;
protected $fillable = [
'name',
'email',
'password',
];
protected $hidden = [
'password',
'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
public function profile()
{
return $this->hasOne(Profile::class, 'user_id');
}
Profile Model
use HasFactory;
protected $table = 'profiles';
protected $guarded = [];
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
Profile Controller
public function render()
{
$userProfile = Profile::where('user_id', Auth::user()->id)->first();
if (!$userProfile) {
$profile = new Profile();
$profile->user_id = Auth::user()->id;
$profile->save();
}
$user = User::find(Auth::user()->id);
return view('profile.index', ['user' => $user]);
}
Profile index.blade.php
<x-app-layout>
<x-slot name="header">
<h2 class="font-semibold text-xl text-gray-800 leading-tight">
{{ __('Dashboard') }}
</h2>
</x-slot>
<div class="py-12">
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
<div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
<div class="p-6 bg-white border-b border-gray-200">
Your Profile!
<div>
<p>Nama :{{ $user->name }}</p>
<p>Email : {{ $user->email }}</p>
<p>Alamat : {{ $user->profile->alamat }}</p>
</div>
</div>
</div>
</div>
</div>
the code above produces an error that is Attempt to read property "address" on null. so how do i solve it?
On your render method, you can do something like this:
if(!\Auth::check()){
abort(401);
}
$user = \Auth::user();
$user->load('profile');
return view('profile.index', ['user' => $user]);
The above code is just the optimization with eager loading. This should give you the profile address:
$user->profile->alamat
Three things you have to confirm while doing this:
Is the user authenticated? If the user is not logged in you might not get data.
Is the route wrap in auth or similar middleware? If not, you might not get auth data.
Is there data in profiles table of the current user currently logged in?

How to link two tables with a pivot table?

Hey so a bit of an overview of the project i want to do. I want to show the user's teams.
When the user logged in and opened the viewteams page. He must show teams he joined/created. To do so i ve done the below processes...
my ViewTeamController
{
public function index()
{
$user=User::first();
$teams=Team::all();
$user->teams()->attach($teams);
return view('teams.viewteams',compact('teams'));
}
public function store()
{
}
}
my User model
public function teams(){
return $this->belongsToMany(Team::class,'team_user','teams_id','users_id');
}
my Team model
public function users(){
return $this->belongsToMany(User::class,'team_user','teams_id','users_id');
}
my migration of the pivot table
public function up()
{
Schema::create('team_user', function (Blueprint $table) {
$table->unsignedBigInteger('users_id');
$table->unsignedBigInteger('teams_id');
$table->index('users_id');
$table->index('teams_id');
$table->timestamps();
});
}
web.php routes
Route::get('/viewteams','ViewTeamController#index');
Route::post('/viewteams','ViewTeamController#store');
my viewteams.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header"><h2 style="text-align:center;">Your Teams</h2></div>
<div class="card-body">
#foreach ($teams as $team)
#foreach($team->users as $user)
{{$user->org_name}}
#endforeach
#endforeach
</div>
</div>
</div>
</div>
</div>
#endsection
my other controller for Creating a team
<?php
namespace App\Http\Controllers;
use App\Team;
use Illuminate\Http\Request;
class CreateTeamController extends Controller
{
public function index(Request $request)
{
return view('teams.createteams');
}
public function store(Request $request)
{
$team=Team::create($request->all());
return redirect()->route('home');
}
}
all my routes
Route::get('/login', function () {
return view('auth/login');
});
Auth::routes();
Route::get('/viewteams','ViewTeamController#index');
Route::post('/viewteams','ViewTeamController#store');
Route::get('/createteams','CreateTeamController#index');
Route::post('/createteams','CreateTeamController#store') ;
Route::get('/home', 'HomeController#index')->name('home');
To achieve currents users teams, first you should get authenticated user id using Auth facade.
After that you can load joined teams for user, using 'with' method. It loads teams relationships.
ViewTeamController
public function index()
{
$user = User::with('teams')->find(Auth::id());
return view('teams.viewteams',compact('user'))
}
viewteams.blade.php
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header"><h2 style="text-align:center;">Your Teams</h2></div>
<div class="card-body">
#foreach ($user->teams as $team)
{{ $team->name }}
#endforeach
</div>
</div>
</div>
</div>
</div>
#endsection
You will need to revisit and update the code which stores data to the users table and the teams user. The easiest way to store the data in a way which populates the pivot table is to use the sync() method as described at https://laravel.com/docs/master/eloquent-relationships#updating-many-to-many-relationships
I'm making some assumptions about names and relationships, buy you may have something like this:
$user = User::find(2);
$user->teams()->sync([4,5]);
In this case, you would put into the pivot table a record for user_id of 2 and team_id of 4, and a second record for a user_id of 2 and a team_id of 5.
If you want to share more code showing route definitions and controllers for how you are currently handling things, we can help with any more specific implementation questions.

Laravel Dropzone with product info

I'm looking for solution to use dropzoneJs in laravel 5.5 while writing my products.
What I want to do is: upload my images and fill my product info then save all together just like WordPress/Joomla etc.
What do I have so far:
Images Table
public function up()
{
Schema::create('images', function (Blueprint $table) {
$table->increments('id');
$table->string('image');
$table->integer('product_id')->nullable()->unsigned();
$table->timestamps();
});
Schema::table('images', function($table) {
$table->foreign('product_id')->references('id')->on('products');
});
}
My form in Products create.blade.php
<div class="row">
<div class="col-md-12">
{!! Form::open([ 'route' => [ 'dropzone.store' ], 'files' => true, 'enctype' => 'multipart/form-data', 'class' => 'dropzone', 'id' => 'image-upload' ]) !!}
{{ csrf_field() }}
<div>
<h4 style="text-align: center;color:#428bca;">Drop images in this area <span class="glyphicon glyphicon-hand-down"></span></h4>
<!-- Input code below Not working yet -->
<input type="text" name="product_id" value="" hidden>
</div>
{!! Form::close() !!}
</div>
</div>
My JavaScript code:
<!-- drozone -->
<script type="text/javascript">
Dropzone.options.imageUpload = {
maxFilesize: 5, //MB
acceptedFiles: ".jpeg,.jpg,.png,.gif"
};
</script>
My ImageController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Image;
use App\Product;
class ImageController extends Controller
{
public function dropzone()
{
return view('dropzone-view');
}
public function dropzoneStore(Request $request)
{
$image = $request->file('file');
$imageName = time().$image->getClientOriginalName();
$image->move(public_path('images'),$imageName);
return response()->json(['success'=>$imageName]);
}
}
And my routes:
Route::get('dropzone', 'ImageController#dropzone');
Route::post('dropzone/store', ['as'=>'dropzone.store','uses'=>'ImageController#dropzoneStore']);
Any Idea On That?

Laravel 5.4 How to update profile of applicant guest that is logged in

I am new to laravel and I want to let the user update his/her profile when logged in. I want to get the ID of the user when updating his/her profile but when I click on the edit view to pass the data using the id I got this error:
(1/1) ErrorException
Missing argument 1 for App\Http\Controllers\Applicant\HomeController::edit()
Here is the code to my controller:
public function edit($id)
{
$applicant = $this->applicantRepository->findWithoutFail($id);
if (empty($applicant)) {
Flash::error('Applicant');
return redirect(route('applicant.home'));
}
return view('applicant-dashboard.edit')->with('applicants', $applicant);
}
public function update($id, UpdateApplicantRequest $request)
{
$applicant = $this->applicantRepository->findWithoutFail($id);
if (empty($applicant)) {
Flash::error('Applicant not found');
return redirect(route('applicant.index'));
}
$input = $request->all();
$cashier = $this->applicantRepository->update([
'name' => $input['name'],
'email' => $input['email'],
'password' => bcrypt($input['password']),
'address' => $input['address'],
'cellphone_no' => $input['cellphone_no']], $id);
Flash::success('Profile updated successfully.');
return redirect(route('applicant.index'));
}
Here is the code in my routes file:
Route::get('/edit', 'HomeController#edit')->name('applicant.edit');
Here is the code in my blade file:
#extends('layouts.app')
#section('content')
<section class="content-header">
<h1>
Applicant Profile
</h1>
</section>
<div class="content">
{{-- #include('adminlte-templates::common.errors') --}}
<div class="box box-primary">
<div class="box-body">
<div class="row" style="padding-left: 20px">
{!! Form::model($applicant, ['route' => ['applicant.update', $applicant->id], 'method' => 'patch']) !!}
#include('applicant-dashboard.fields')
{!! Form::close() !!}
</div>
</div>
</div>
</div>
#endsection
You need to pass the id into your route:
Route::get('/edit/{id}', 'HomeController#edit')->name('applicant.edit');
You pass the ID into web.php:
Route::get('edit/{ID}', 'HomeController#edit')->name('applicant.edit');

Categories