Our Black Friday sale is now live! All individual subscriptions are 50% OFF. This week only!

artisticre

artisticre

Member Since 2 Years Ago

Experience Points
9,140
Total
Experience

860 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed
21
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start your engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

Level 2
9,140 XP
Nov
09
2 weeks ago
Activity icon

Replied to Array_key_exists

So why am I getting this error?

array_key_exists(): The first argument should be either a string or an integer

public function addItem($id,$product)
{
    $price = (int) str_replace("$","",$product->price);
    
    if(isset($id,$this->items)) 
    {
        $productToAdd = $this->items($id);
        $productToAdd['quantity']++;
    } else{
        $prodctToAdd = ['quantity'=>1,'price'=> $price , 'data'=>$product];
    }
    $this->items[$id] = $prodctToAdd;
    $this->totalQuantity++;
    $this->totalPrice = $this->totalPrice * $price;
}

Activity icon

Started a new Conversation Array_key_exists

I understand array_key_exists has been depreciated. How would I change this line in this case?

if(array_key_exists($id,$this->items))	
Oct
28
4 weeks ago
Activity icon

Started a new Conversation $image_tmp = Input::file('image');

In Laravel 8, Input is gone. Suggested to use

 $image_tmp = Request::file('image');

but I get this error

Non-static method Illuminate\Http\Request::file() should not be called statically
Oct
16
1 month ago
Activity icon

Replied to Target Class [Database\Seeders\LaratrustSeeder] Does Not Exist.

nope. I did that and composer dump-autoload. Then I ran php artisan db:seed and still can't find the laratrust class

Activity icon

Replied to Target Class [Database\Seeders\LaratrustSeeder] Does Not Exist.

so like this?

$this->call(\LaratrustSeeder::class);
Activity icon

Replied to Target Class [Database\Seeders\LaratrustSeeder] Does Not Exist.

I have the following and I did composer dump-autoload and still get the error.

  "autoload": {
        "psr-4": {
            "App\": "app/",
            "Database\Factories\": "database/factories/",
            "Database\Seeders\": "database/seeders/"
        }
    },
Activity icon

Started a new Conversation Target Class [Database\Seeders\LaratrustSeeder] Does Not Exist.

Trying to install LaratrustSeeder and when its time to run db:seed I get target class does not exist.

Laratrust Seeder

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Config;

class LaratrustSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return  void
     */
    public function run()
    {
        $this->truncateLaratrustTables();

        $config = config('laratrust_seeder.roles_structure');
        $mapPermission = collect(config('laratrust_seeder.permissions_map'));

        foreach ($config as $key => $modules) {

            // Create a new role
            $role = \App\Models\Role::firstOrCreate([
                'name' => $key,
                'display_name' => ucwords(str_replace('_', ' ', $key)),
                'description' => ucwords(str_replace('_', ' ', $key))
            ]);
            $permissions = [];

            $this->command->info('Creating Role '. strtoupper($key));

            // Reading role permission modules
            foreach ($modules as $module => $value) {

                foreach (explode(',', $value) as $p => $perm) {

                    $permissionValue = $mapPermission->get($perm);

                    $permissions[] = \App\Models\Permission::firstOrCreate([
                        'name' => $module . '-' . $permissionValue,
                        'display_name' => ucfirst($permissionValue) . ' ' . ucfirst($module),
                        'description' => ucfirst($permissionValue) . ' ' . ucfirst($module),
                    ])->id;

                    $this->command->info('Creating Permission to '.$permissionValue.' for '. $module);
                }
            }

            // Attach all permissions to the role
            $role->permissions()->sync($permissions);

            if(Config::get('laratrust_seeder.create_users')) {
                $this->command->info("Creating '{$key}' user");
                // Create default user for each role
                $user = \App\Models\User::create([
                    'name' => ucwords(str_replace('_', ' ', $key)),
                    'email' => $key.'@app.com',
                    'password' => bcrypt('password')
                ]);
                $user->attachRole($role);
            }

        }
    }

    /**
     * Truncates all the laratrust tables and the users table
     *
     * @return    void
     */
    public function truncateLaratrustTables()
    {
        $this->command->info('Truncating User, Role and Permission tables');
        Schema::disableForeignKeyConstraints();
        DB::table('permission_role')->truncate();
        DB::table('permission_user')->truncate();
        DB::table('role_user')->truncate();
        if(Config::get('laratrust_seeder.truncate_tables')) {
            \App\Models\Role::truncate();
            \App\Models\Permission::truncate();
        }
        if(Config::get('laratrust_seeder.truncate_tables') && Config::get('laratrust_seeder.create_users')) {
            \App\Models\User::truncate();
        }
        Schema::enableForeignKeyConstraints();
    }
}

Database Seeder

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        $this->call(LaratrustSeeder::class);

    }
}

Oct
11
1 month ago
Activity icon

Replied to Show Trying To Get Property 'title' Of Non-object

Oh my gosh. Stupid mistake. Absolutely! Thank you just needed another pair of eyes

Activity icon

Started a new Conversation Show Trying To Get Property 'title' Of Non-object

I can't find my error.

Controller

 public function show($id)
    {
        $productdisplay = Product::find($id);
        return view('shop.show')->with('productdisplay',$productdisplay);
    }

show page

 @foreach($productdisplay as $prod)
{{$prod->title}}

@endforeach

dd output

App\Models\Product {#1249 ▼
  #fillable: array:5 [▼
    0 => "imagePath1"
    1 => "imagePath2"
    2 => "title"
    3 => "description"
    4 => "price"
  ]
  #connection: "mysql"
  #table: "products"
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:8 [▶]
  #original: array:8 [▼
    "id" => 1
    "imagePath1" => "https://i.pinimg.com/736x/44/5b/85/445b85fbd3bb9020dc698c1c78bb7ac2.jpg"
    "imagePath2" => "https://i.pinimg.com/736x/44/5b/85/445b85fbd3bb9020dc698c1c78bb7ac2.jpg"
    "title" => "Women Necklace"
    "description" => "Women necklace made from colored beads and charms"
    "price" => 10
    "created_at" => "2020-10-12 00:17:25"
    "updated_at" => "2020-10-12 00:17:25"
  ]
  #changes: []
  #casts: []
  #classCastCache: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
Oct
08
1 month ago
Activity icon

Started a new Conversation Admin Password Reset Email Link

Where in laravel does the password reset link get changed? I have a user and and admin. Everything is working except when the admin resets the password, in the email it still links to the user token and not the admin token. See below. How do I change this link from http://localhost:8000/password/reset to http://localhost:8000/admin/password/reset


If you’re having trouble clicking the "Reset Password" button, copy and paste the URL below into your web browser: http://localhost:8000/password/reset/1baa6c5dfb8b4541d713d7966eebbb003eeb04812ae8310fe06ad2deec326798?email=artisticre%40hotmail.com
Oct
01
1 month ago
Activity icon

Replied to Multi-Auth

Could you give me an example?

Activity icon

Started a new Conversation Multi-Auth

OK I have middleware working to where the user logs in and it goes to the dashboard. Cannot access the admin dashboard. But if the admin logs in, it goes to the admin dashboard but if you change the url to user dashboard, the admin can still access this? What am I missing?

Admin Middleware

<?php

namespace App\Http\Middleware;

use Closure;

class Admin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(auth()->user()->is_admin == 1){
            return $next($request);
        }
   
        return redirect('dashboard')->with('error',"Only admin can access!");
    }
}

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\Contracts\Support\Renderable
     */
    public function index()
    {
        return view('dashboard');
    }

    public function handleAdmin()
    {
        return view('admin-dashboard');
    }    
}

Routes

<?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::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/dashboard', [App\Http\Controllers\HomeController::class, 'index'])->name('dashboard')->middleware('auth');

Route::get('admin-dashboard', [App\Http\Controllers\HomeController::class,'handleAdmin'])->name('admin.route')->middleware('admin');
Sep
24
2 months ago
Activity icon

Replied to Laravel 8 Multi - Authentication

does this still apply to laravel 8?

Activity icon

Started a new Conversation Laravel 8 Multi - Authentication

Hey all,

I am looking for a step by step tutorial on creating an admin section to Laravel 8. I barely got through authentication with fortify but haven't found anything that goes over adding an admin dashboard and admin login as well. If anyone can suggest a good tutorial, it will be so helpful.

Thanks

Sep
22
2 months ago
Activity icon

Started a new Conversation Laravel 8 RedirectTo

I have this code. It works when someone registers for an account but if I put it on the login page, it always logs in to the home page.

Login Controller

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
 
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    public function redirectTo()
    {
      if(Auth::user()->hasRole('admin')) {
          $this->redirectTo = route('admin-dashboard');
          return $this->redirectTo;
      } elseif
      (Auth::user()->hasRole('customer')) {
          $this->redirectTo = route('customer-dashboard');
          return $this->redirectTo;
      }
      return $this->redirectTo;
}
}

Route

Route::get('customer-dashboard','[email protected]')->middleware('can:customer')->name('customer-dashboard');
Route::get('admin-dashboard','[email protected]')->middleware('can:admin')->name('admin-dashboard');

Home Controller

 public function getCustomerDashboard()
    {
        return view('dashboard');
    }

    public function getAdminDashboard()
    {
        return view('admin.dashboard');
    }

Middleware

Gate::define('admin', function($user) {
            return $user->hasRole('admin');
            return redirect('/login');
        });

        Gate::define('customer',function($user){
            return $user->hasRole('customer');
            return redirect('/login');
        });
Sep
17
2 months ago
Activity icon

Awarded Best Reply on Displaying Wrong

I do. I figured it out though. {{ Session::get('cart')->totalQuantity }} I removed the spaces like this {{Session::get('cart')->totalQuantity}} and it works.

Activity icon

Replied to Displaying Wrong

I do. I figured it out though. {{ Session::get('cart')->totalQuantity }} I removed the spaces like this {{Session::get('cart')->totalQuantity}} and it works.

Activity icon

Started a new Conversation Displaying Wrong

I have this simple code that doesn't seem to work. It is just displaying {‌{ Session::get('cart')->totalQuantity }} instead of the number. What am I doing wrong?

@if(Session::has('cart'))
 
									<span class="cart-with-numbers">
													   {‌{ Session::get('cart')->totalQuantity }}
									 </span>
									 
							   @endif
Sep
11
2 months ago
Activity icon

Started a new Conversation CategoriesTableSeeder Error

Not sure why I am getting this error.

Error

Call to undefined function Database\Seeders\factory()

  at C:\wamp64\www\haylee\database\seeders\CategoriesTableSeeder.php:24
     20▕             'parent_id'     =>  null,
     21▕             'menu'          =>  0,
     22▕         ]);
     23▕
  ➜  24▕         factory(App\Models\Category::class, 5)->make();
     25▕     }
     26▕ }

  1   C:\wamp64\www\haylee\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php:37
      Database\Seeders\CategoriesTableSeeder::run()

  2   C:\wamp64\www\haylee\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php:37
      call_user_func_array([])

Seeder

<?php

namespace Database\Seeders;
use App\Models\Category;
use Faker\Factory as Faker;
use Illuminate\Database\Seeder;

class CategoriesTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Category::create([
            'name'          =>  'Root',
            'description'   =>  'This is the root category, don\'t delete this one',
            'parent_id'     =>  null,
            'menu'          =>  0,
        ]);

        factory(App\Models\Category::class, 5)->make();
    }
}
Sep
10
2 months ago
Activity icon

Started a new Conversation Target Class [Admin\LoginController] Does Not Exist

Can't find my error. Help!

routes

<?php

use Illuminate\Support\Facades\Route;

Route::group(['prefix'  =>  'admin'], function () {

Route::get('login', 'Admin\[email protected]')->name('admin.login');
Route::post('login', 'Admin\[email protected]')->name('admin.login.post');
Route::get('logout', 'Admin\[email protected]')->name('admin.logout');

Route::get('/', function () {
    return view('admin.dashboard.index');
});

});

LoginController

<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    use AuthenticatesUsers;

    /**
     * Where to redirect admins after login.
     *
     * @var string
     */
    protected $redirectTo = '/admin';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest:admin')->except('logout');
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showLoginForm()
    {
        return view('admin.auth.login');
    }
}
Sep
02
2 months ago
Activity icon

Replied to PDOExcetion('Could Not Find Driver')

I did. still the same error. I do not see extension=php_pdo_mysql.dll in my php.ini. How do I get it there?

Activity icon

Replied to PDOExcetion('Could Not Find Driver')

the error I am getting now after dbal is

Doctrine\DBAL\Driver\PDOException::("could not find driver")

Activity icon

Replied to PDOExcetion('Could Not Find Driver')

I see extension=pdo_mysql not commented out but nothing about the .dll

Activity icon

Replied to PDOExcetion('Could Not Find Driver')

Thanks I did that. Nothing worked

Activity icon

Started a new Conversation PDOExcetion('Could Not Find Driver')

I have a fresh install of composer, wamp64, and laravel 7. Trying to migrate my tables and I get the PDO Exception error. Someone said it could be a PHP conflict but I have no idea how to fix it.

php -v

PHP 7.4.9 (cli) (built: Aug 4 2020 11:51:50) ( NTS Visual C++ 2017 x64)
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
Wamp64 PHP version used is 7.4.9

I am running on Windows 10

Aug
27
2 months ago
Activity icon

Awarded Best Reply on Buefy Checkbox Not Showing

I had my navbar include inside That was the cause

Activity icon

Replied to Buefy Checkbox Not Showing

I had my navbar include inside That was the cause

Activity icon

Started a new Conversation Buefy Checkbox Not Showing

Not sure what I am doing wrong. Can anyone spot something?

App.js

require('./bootstrap')
window.Vue = require('vue')
import Buefy from 'buefy'
Vue.use(Buefy)

//Must have to bind this to work with VUE js
const app = new Vue({
 el: '#app'
});

layouts.app

  <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}" defer></script>
    @yield('scripts')
</body>
</html>

view

<div class="field">
                    <b-checkbox :value="true"
                    type="is-info">
                        remember
                    </b-checkbox>
                </div>
Aug
25
3 months ago
Activity icon

Awarded Best Reply on Call To A Member Function IsValid() On Null

Figured it out. Typo in the validation

            'email' => 'required|email:max:255',

should be

            'email' => 'required|email|max:255',
Activity icon

Replied to Call To A Member Function IsValid() On Null

Figured it out. Typo in the validation

            'email' => 'required|email:max:255',

should be

            'email' => 'required|email|max:255',
Activity icon

Started a new Conversation Call To A Member Function IsValid() On Null

I know its on the validation because if I take the validation out, it posts a comment. Not sure what to fix.

create function

public function store(Request $request,$post_id)
    {
        

        $this->validate($request, array(
            'name' => 'required|max:255',
            'email' => 'required|email:max:255',
            'comment' => 'required|min:5|max:2000'
           
        ));

        $post = Post::find($post_id);
        $comment = new Comment();
        $comment->name = $request->name;
        $comment->email = $request->email;
        $comment->comment = $request->comment;
        $comment->approved = true;
        $comment->post()->associate($post);
        $comment->save();
        Session::flash('success','Comment was added!');
        return redirect()->route('blog.single',[$post->slug]);
    }

migration

public function up()
    {
        Schema::create('comments', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email');
            $table->text('comment');
            $table->boolean('approved');
            $table->integer('post_id')->unsigned();
            $table->timestamps();
        });

        Schema::table('comments', function($table) {
        $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');

    });
Aug
19
3 months ago
Activity icon

Awarded Best Reply on Select2

Here is the error but I thought we could add scripts just on single views if we don't want to load it throughout the project

Templates should only be responsible for mapping the state to the UI. Avoid placing tags with side-effects in your templates, such as <script>, as they will not be parsed.

45 |          </div>
46 |          </main>
47 |  <section class="footer">test</section>
   |                                         
48 |  <script src="http://localhost:8000/js/select2.min.js"></script>
   |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
49 |  <script type="text/javascript">
   |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
50 |    $(document).ready(function() {
   |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
51 |      $('.select2-multi').select2();
   |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
52 |  });
   |  ^^^
53 |   </script>
   |  ^^^^^^^^^^
54 |  
   |  
55 |  
   |  
56 |  </div>
Activity icon

Replied to Select2

Here is the error but I thought we could add scripts just on single views if we don't want to load it throughout the project

Templates should only be responsible for mapping the state to the UI. Avoid placing tags with side-effects in your templates, such as <script>, as they will not be parsed.

45 |          </div>
46 |          </main>
47 |  <section class="footer">test</section>
   |                                         
48 |  <script src="http://localhost:8000/js/select2.min.js"></script>
   |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
49 |  <script type="text/javascript">
   |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
50 |    $(document).ready(function() {
   |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
51 |      $('.select2-multi').select2();
   |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
52 |  });
   |  ^^^
53 |   </script>
   |  ^^^^^^^^^^
54 |  
   |  
55 |  
   |  
56 |  </div>
Activity icon

Started a new Conversation Select2

Not sure if this is a Laravel or Javascript question but here goes. I am trying to use a script called select2. I just want to add it to a particular blade view and not throughout my entire project. In my template I have setup sections @yield('stylesheets') in the head and @yield('scripts') just below the body tag. Its like its not connecting to either script. Is there something I am missing?

In my view I have

@section('stylesheets')
{!! Html::style('css/select2.min.css') !!}
@endsection

This is at the bottm.

@section('scripts')
{{Html::script('js/select2.min.js')}}
<script type="text/javascript">
  $(document).ready(function() {
    $('.select2-multi').select2();
});
 </script>
@endsection

Oh the form I am using

 <select name="tags" class="select2-multi form-control" multiple="multiple">
          @foreach($tags as $tag)
            <option value="{{$tag->id}}">{{$tag->name}}</option>
            @endforeach
        </select> 
Aug
18
3 months ago
Activity icon

Started a new Conversation Relationships And Displaying Data.

I have two models Users, Posts. Either I am not doing the relationships correctly or there is something I am missing but it is not displaying anything. No error, just empty field on my view

User Model

  public function posts()
   {
       return $this->hasMany('App\Post');
   }

Post Model

public function users(){
        return $this->belongsTo('App\User');
    }

Controller

 public function getSingle($slug)
    {
       $post = Post::where('slug', '=', $slug)->first();
       return view('blog.single')->with('post', $post);

    }

How I Display The Data

{{$post->user['name']}}
Aug
17
3 months ago
Activity icon

Replied to Password Reset

This is my ResetPasswordController and it still goes to /home

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\ResetsPasswords;

class ResetPasswordController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Password Reset Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling password reset requests
    | and uses a simple trait to include this behavior. You're free to
    | explore this trait and override any methods you wish to tweak.
    |
    */

    use ResetsPasswords;

    /**
     * Where to redirect users after resetting their password.
     *
     * @var string
     */
protected $redirectTo = '/login';


}

Activity icon

Started a new Conversation Password Reset

Quick Question:

I have the password reset working but when it resets the password, it redirects to /home when I want it to redirect to /login. What file controls this action?

Activity icon

Started a new Conversation DB Question

I have two tables Users and Posts. I am trying to understand relationships. I have already created these tables and everything is working. Now I want to create a controller that lists the posts based on the user_id. Would I put a column in the Posts table called user_id to be able to query the db or is there a better way?

User Model

 public function posts() {
        return $this->belongsToMany('App\Post');
    }

Post Model

public function users(){
        return $this->belongsToMany('App\User');
    }

Users Table

 public function up()
    {
        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();
        });
    }

Posts Table

public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('body');
            $table->timestamps();
        });
    }
Aug
13
3 months ago
Activity icon

Replied to Why Am I Getting This Error?

so how do I do a seperate template for one page?

Activity icon

Started a new Conversation Why Am I Getting This Error?

I know it is probably something pretty simple but for the life of me I cannot figure out why I get this error:

The requested resource /blog was not found on this server.

Route

Route::resource('/blog','BlogController');

BlogController

public function index()
    {
        return view('blog.index');
    }

Blog.index

@extends('layouts.bloglayout')

@section('content')
TEST BLOG PAGE
@endsection

bloglayout

<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <!-- Scripts -->
    <script src="{{ asset('blog/js/app.js') }}" defer></script>

      <!-- Styles -->
  <!-- Custom styles for this template -->
  <link href="blog/css/clean-blog.min.css" rel="stylesheet"></head>
<body>
    @include('inc.navbar')
   @include('inc.jumbotron') 
    <div id="app">
        

        <main class="py-4">
            <div class="container">
            @include('inc.alerts')
            
            @yield('content')
        </div>
        </main>
    </div>
    <script src="blog/js/clean-blog.min.js"></script>
</body>
</html>
Aug
03
3 months ago
Activity icon

Started a new Conversation Vue Script Not Working

I have this code when on my individual page, does not work. But if I put it in app.js, it works but there is an error because it cant find $user. How do I get it to work on my blade view?

@section('scripts')
  <script>

    var app = new Vue({
      el: '#app',
      data: {
        rolesSelected: {!! $user->roles->pluck('id') !!}
      }
    });

  </script>
@endsection

my layout where I yield scripts

<div class="management-area" id="app">
      
            @yield('content')
                  </div>
                  <script src="{{ asset('js/app.js') }}" defer></script>
    @yield('scripts') 
</body>
</html>
Jun
26
4 months ago
Activity icon

Replied to String Back To Checked Checkbox

@snapey

Here is my form collection

<div class="pretty p-default">
        <input type="checkbox" name="clergy[]" value="Spiritual Director" />
        <div class="state p-info">
            <label class="lead text-primary">Spiritual Director</label>
        </div>
    </div>

    <!-- warning -->
    <div class="pretty p-default">
        <input type="checkbox" name="clergy[]" value="Lay Team" />
        <div class="state p-warning">
            <label class="lead text-primary">Lay Team</label>
        </div>
    </div>

    <!-- danger -->
    <div class="pretty p-default">
        <input type="checkbox" name="clergy[]" value="Wherever Needed" />
        <div class="state p-danger">
            <label class="lead text-primary">Wherever Needed</label>
        </div>
    </div>

And my store controller

        'clergy' => ['required'],
       $clergyString = implode(",", $request->get('clergy'));
         $team->clergy =  $clergyString;
Jun
25
5 months ago
Activity icon

Replied to String Back To Checked Checkbox

@snapey I have it working if I have a list of them such as $clergy = 'Spiritual Director,Wherever Needed' but I want to change this to the following and have it pulled from the database. Right now the code below works but nothing is checked. Its pulling the data but the foreach loop isn't looking at the $userroles for some reason so nothing is checked.

When I dd I get $userroles

Illuminate\Support\Collection {#1311 ▼
  #items: array:3 [▼
    0 => "[{"clergy":"Spiritual Director"
    1 => "Wherever Needed""
    2 => ""id":6}]"
  ]
}
$clergy = DB::table('users')
                ->join('teamapp', 'teamapp.user_id', '=' ,'users.id')
                ->select(
                    'clergy',
                    'teamapp.id'
                    )
                    ->where('teamapp.id', '=', $id)
                    ->get();
Activity icon

Replied to String Back To Checked Checkbox

I got this working if I use

$clergy = 'Table Leader,Head Palanca,Mime';

but I want to do this

$clergy = DB::table('users')
                ->join('teamapp', 'teamapp.user_id', '=' ,'users.id')
                ->select(
                    'clergy',
                    'teamapp.id'
                    )
                    ->where('teamapp.id', '=', $id)
                    ->get();

If I do dd($userroles); I get

Illuminate\Support\Collection {#1311 ▼
  #items: array:3 [▼
    0 => "[{"clergy":"Spiritual Director"
    1 => "Wherever Needed""
    2 => ""id":6}]"
  ]
}

So I know its pulling the correct data, but on my loop, nothing is getting checked. If I change $clergy back to the list, I get them checked.

@foreach($allroles as $role)
  <label for="check-{{ $loop->index }}">{{ $role }}
      <input type='checkbox' value="{{ $role }}" id="check-{{ $loop->index }}"
	  @if($userroles->contains($role)) checked @endif
      />
  </label>
@endforeach 

Jun
24
5 months ago
Activity icon

Replied to String Back To Checked Checkbox

I got this working. Thank you so much. But how do I make this part dynamic?

                $clergy = 'Spiritual Director,Wherever Needed';

I tried this and when I dd($clergy) it shows in the array but does not check the boxes.

$clergy = DB::table('users')
                ->join('teamapp', 'teamapp.user_id', '=' ,'users.id')
                ->select(
                    'clergy',
                    'teamapp.id'
                    )
                    ->where('teamapp.id', '=', $id)
                    ->get();
                       
                $userroles = collect(explode(',',$clergy));

                return view('teamapplication.show')->with('team', $team)->with('userroles', $userroles)->with('allroles', $allroles);

My loop

@foreach($allroles as $role)
<div class="pretty p-icon p-round">
<input disabled type='checkbox' value="{{ $role }}" id="check-{{ $loop->index }}"
	  @if($userroles->contains($role)) checked @endif
      />
      <div class="state p-warning">
      <label for="check-{{ $loop->index }}">{{ $role }}
      
      </label>
    
      </div>
</div>
@endforeach 
Jun
23
5 months ago
Activity icon

Replied to String Back To Checked Checkbox

What do you all think of this? Is this a good way to do this or not? For each of the checkboxes

<input type="checkbox" value="Sacristan" id="teamexperience" name="teamexperience[]"
  @if(in_array("Sacristan", explode(",", $t->teamexperience)))
    {{"checked" }}
@endif />
Activity icon

Replied to String Back To Checked Checkbox

I came up with this but I get an error syntax error, unexpected ','

@foreach($team as $clergy)
     <input type="checkbox" name="clergy[]" value="{{$clergy->id}}" {{($clergy->id, explode(',', $clergy->clergy))  ? 'selected' : ''}}>{{$clergy->clergy}}
   @endforeach
Activity icon

Replied to String Back To Checked Checkbox

They will only be present if they are chosen from the form. This is the list the user can chose from, but the db will only have their choices. I am really lost. Is it possible to show an example?